Search code examples
javascriptreactjsreact-testing-library

React testing library does not finish function test


I got this mock code right here on stackoverflow, but it's not working, the test calls the handleLogout function, but it doesn't execute the navigate('/login'), it's like the test runs only until the api call and ends the test.

//headerApp.tsx
const handleLogout = async () => {
     await api.post('auth/logout');
     navigate('/login');
}

//headerApp.test.tsx

const mockedNavigate = jest.fn();

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom') as any,
  useNavigate: () => mockedNavigate
}));


test('check logout', async () => {
    server.use(
        rest.post('http://localhost:2001/backend_ihm/auth/logout', (req, res, ctx) => {
            return res(ctx.status(200))
        }),
    )

    const { getByTestId } = render(
        <Router>
            <AuthProvider>
                <HeaderApp links={links} activeLink={{ route: 1 }} />
            </AuthProvider>
        </Router>
    );

    await screen.findByText('TESTE');

    const linkLogout = getByTestId('link-logout');

    fireEvent.click(linkLogout);

    expect(mockedNavigate).toHaveBeenCalledWith('/login');
});


Solution

  • The comment from @AviCohenNehemia helped me, this is the answer:

    await waitFor(() => expect(mockedNavigate).toHaveBeenCalledWith('/login'));