1

I'm trying to test a failure on my API call with MSW, testing library and RTK Query. More on the context: I'm testing a hook and I'm calling a function and expect an API fail to assert that an error callback is call.

This is the code, the test call the check auth function and then pass in authenticateUser and then the api fail as expected (see test file):

Code

const checkAuth = useCallback(async () => {
    const token = await checkToken();

    if (!isAuthenticated && token) {
      await authenticateUser(token);
    } else {
      dispatch(clearAuth);
      onAuthFailureCallback?.();
    }
  }, [
    isAuthenticated,
    authenticateUser,
    checkToken,
    dispatch,
    onAuthFailureCallback,
  ]);

const authenticateUser = useCallback(
    async (token: string) => {
      try {
        await startAuthenticate(token, false).unwrap();
        onAuthSuccessCallback?.();
      } catch (err) {
        onAuthFailureCallback?.(err);
      }
    },
    [startAuthenticate, onAuthSuccessCallback, onAuthFailureCallback],
  );

Test

it('given the user is not authenticated and the authentication fail an error should be sent back', async () => {
      server.use(
        rest.get(`${API_BASE_URL}api/v2.1/session`, (req, res, ctx) => {
          ctx.set('Authorization', 'Bearer token');
          return res(
            ctx.status(401),
            ctx.json({
              message: 'Could not be identified',
            }),
          );
        }),
      );

      jest
        .spyOn(sessionStorageUtils, 'getUserToken')
        .mockResolvedValue('my token');

      const appStore = createStore({
        preloadedState: {
          session: { ...sessionStateMock, isAuthenticated: false },
        },
      });

      const { result } = renderHook(useAuth, {
        initialProps: {
          onAuthFailureCallback: onAuthFailureCallbackMock,
          onAuthSuccessCallback: onAuthSuccessCallbackkMock,
        },
        wrapper: props => <HookWrapper {...props} appStore={appStore} />,
      });

      await act(async () => {
        await result.current.checkAuth();
      });

      expect.assertions(1);
      return expect(onAuthFailureCallbackMock).toHaveBeenCalledWith({
        status: 401,
        data: { message: 'Could not be identified' },
      });
    });
  });

The assertion work fine but jest still throw the api error and make the test fail

Jest error

thrown: Object {
  "error": Object {
  "data": Object {
    "message": "Could not be identified",
  },
  "status": 401,
  },
...
}

Did you have an idea how to make the test pass and make jest not yield on api error?

  • I've try to use try / catch in my test file
  • I've try to use the specific jest assertion expect.rejects

0 Answers0