0

I am trying to test some api calls in Jest, however the test is failing as the api call is dependent on another call to complete first, so the returned value is empty as opposed to what should be in there. I am using react-query for the api calls. Or is there a better or other way to test async calls? I am using MSW also, to intercept the api calls.

Async call

const getApi = async (): Promise<any> => {
   const response = await axios.get(`https://www.xxxxx`).then(res => res.data);
   return response;
}

test

const queryClient = new QueryClient()

describe('Comp1 tests', (): void => {
    beforeEach(() => {
        jest.useFakeTimers();
    });


    it('Should give correct response with render', async () => {
        renderWithQueryClient(<QueryClientProvider client={queryClient}><Comp1 /></QueryClientProvider>);
        expect(await screen.findByTestId('main-header')).toBeInTheDocument();
    });
});

I get:

Unable to find an element by: [data-testid="main-header"]

Sole
  • 3,100
  • 14
  • 58
  • 112
  • Im not sure if this is the answer because i dont fully get your question but if you want to wait for your async stuff to be finished before you test, wrap your render in an act() call like described here. https://reactjs.org/docs/test-renderer.html#testrendereract – Andreas Jagiella Dec 22 '21 at 12:48
  • Yes, so it's just so the async stuff to finish, but that did not work - test still fails as the test is running before the mock call is called / finish – Sole Dec 22 '21 at 12:50

0 Answers0