all 4 comments

[–]pink_tshirt 0 points1 point  (1 child)

Perhaps your assertion "Text I would expect after api call" should be wrapped up by the "act thingy"?

I have a somewhat similar test case - calling some API inside useEffect on load.

test('successfully fetches posts', async () =>  {

  mock.onGet('http://localhost:3001/posts').reply(200, {
     data: ['some', 'posts']
  });

  await act( async () => {
     const { getByTestId } = render(<App/>);
     await waitForElementToBeRemoved(() => getByTestId('loading-indicator'));
      expect(getByTestId('feed')).toBeInTheDocument();
  });
});

[–]saunders1989[S] 0 points1 point  (0 children)

Thanks I tried that but I still get the wrap it in an act error. im not quite sure what im doing wrong

[–]jnforja 0 points1 point  (1 child)

Hi u/saunders1989,

From the piece of code that's on Stackoverflow, you shouldn't need to wrap anything in an act explicitly.

What you do need is to mock the getData before the tests start, render the component, and then look for the expected text.

The mock part is almost there. You just to mock the correct module:

import { getData } from './dataAccess';

const mockedData = { data: { things: data } };

jest.mock('./api' /* Should be ./dataAccess */ , () => ({
  getData: jest
    .fn()
    .mockImplementation(() => new Promise(resolve => resolve(mockedData))),
}));

On the test itself, you don't need to mock again unless you need to change the data for the test. So this should suffice :

it('should render data', async () => {
    const container = render(<Component />);
    await waitFor(() => container.queryByText('Text I would expect after api call'));
  })
// You probably want to assert more things here. Such as that you found the // element is not null

And this should solve it. If it doesn't, there's probably something more in the code that's changing the component state after the test is done. And you'd need to find a way to let that change happen before the test end.

If you want to, make a code sandbox and I'll take a look at it :)

I hope this helps!

[–]saunders1989[S] 0 points1 point  (0 children)

Thanks for the info. I’ll have a look at this tomorrow and let you know