Test is broken with Cannot update a component (`SellerDescription`) while rendering a different component


I have a test failing with:

Warning: Cannot update a component (`SellerDescription`) while rendering a different component (`Truncate`). To locate the bad setState() call inside `Truncate`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
          at Truncate (.../components/Vdp/SellerProfile/__tests__/SellerDescription.test.tsx:57:5)
          at div
          at SellerDescription (.../components/Vdp/SellerProfile/SellerDescription.tsx:45:45)

The error raised by component code below:

  import Truncate from 'react-truncate';
  ...
  <Truncate
    lines={isTruncated && collapsedLinesToShow}
    onTruncate={(truncatedText): void => {
      // when the text is over the truncate limit but we expand via the button do nothing
      if (truncatedText === false && isTextOverTruncateLimit === true) {
        return;
      }
      setIsTextOverTruncateLimit(truncatedText);
    }}
  >
    {description}
  </Truncate>

The actual problem seems to be with the mock below:

let mockIsTruncated = true;
jest.mock('react-truncate', () => {
  return function Truncate({
    lines,
    onTruncate,
    children,
  }: {
    onTruncate: (isTruncated: boolean) => void;
    lines: number | boolean;
    children: string;
  }): JSX.Element {
    onTruncate(mockIsTruncated);
    const truncated = typeof lines === 'number' ? children.slice(0, lines as number) : children;
    return <>{truncated}</>;
  };
});

I need this mock to run the tests

describe('when the description is short', () => {
  beforeEach(() => {
    mockIsTruncated = false;
  });
  it('does not show the expand button', () => {
    ({ queryByText } = render(<SellerDescription description={shortDescription} />));

    expect(queryByText(I18n.t('vdp.showMore') as string)).toBeNull();
  });
});

describe('when the description is long', () => {
  beforeEach(() => {
    mockIsTruncated = true;
  });
  it('does not show the expand button', () => {
    ({ getByText } = render(<SellerDescription description={shortDescription} />));

    expect(getByText(I18n.t('vdp.showMore') as string)).toBeTruthy();
  });
});

What is the correct way to implement this? How do I fix the test [mock]?

Source: React – Stack Overflow

September 22, 2021
Category : News
Tags: javascript | jestjs | mocking | reactjs | unit testing

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.