0
votes

I have a component for which I have this test

test('Some Test', () => {
  const { getByTestId } = render(<SomeComponent>Some String</SomeComponent>);

  const componentNode = getByTestId('primary');

  expect(componentNode).toEqual('Some String');
});

This component accepts an optional prop loading (boolean) which is by default false. When loading is true, a spinner is rendered instead of any children passed to this component. I want to create a test (and probably change the existing one) for when I pass the loading prop (to test that the component changes state). How can I do it the best way?

2

2 Answers

0
votes

You need to mock loading prop in test and to pass it to your component. I guess it is true or false. But since in your test code you do not forward any loading prop, I assume it is then undefined inside component.

In case of false value, you need to verify that those conditionally rendered elements are not rendered. In case when you want to test that some element is not rendered, React Testing Library offers API just for that. From the docs:

queryBy...: Returns the first matching node for a query, and return null if no elements match. This is useful for asserting an element that is not present.

So inside your test, you need something like: expect(queryBy*(...)).not.toBeInTheDocument();

And for case when you forward true as value for loading prop, you need to verify that your elements are rendered using the await findBy*() API. You can take a look for more in link provided above.

0
votes

You need to pass loading flag value as a prop and then assert based on props passed. Ex:

test('Some Test', () => {
   render(<SomeComponent loading={true}>Loading</SomeComponent>);
    
   const loading = screen.queryByText('Loading')
    
   expect(loading).toBeInTheDocument();
});


test('Some Test', () => {
    render(<SomeComponent loading={false}>Hello</SomeComponent>);
            
    const hello = screen.queryByText('Hello')
            
    expect(hello).toBeInTheDocument();
});

Also you can refers to https://kentcdodds.com/blog/common-mistakes-with-react-testing-library which suggest to use screen for querying.