简体   繁体   中英

UnhandledPromiseRejectionWarning when testing React component with Jest

So I want to test my Login component with Jest and React Testing Library.
Tests pass but I receive a:

"UnhandledPromiseRejectionWarning".

How do I get rid of this message?

This is the function I mock in top of the test file:

jest.mock('../../../api/endpoints/auth/login/login', () => {
  return {
    login: jest.fn()
  };
});

And this is the function usage directly in test:

(login as jest.Mock).mockResolvedValueOnce(() => ({
  messages: ["Password is not correct"],
  isError: true
}));
act(() => {
  fireEvent.click(submitButton, leftClick);
});

await wait(() => {
  expect(getByTextLogin("Password is not correct")).toBeInTheDocument();
  expect(window.location.href).toContain('/login');
});

Maybe I'm missing something when mocking an async function?

Please put the code in the question, not pictures.

You're not handling the case of the promise rejecting when using async/await. Wrap your await in a try/catch.

Here's a link to jest's documentation highlighting this: Jest Async

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM