Mocked class method only returns undefined

Viewed 20

I'm testing a React class component which relies on a service for retrieving the user auth.

  async populateState() {
    const result = await authService.getUserAuthenticationStatus();
    const { user, isAuthenticated } = result;
    this.setState({
      isAuthenticated,
      user
    });
  }

So, I would like to mock the return value for getUserAuthenticationStatus like so:

jest.mock('./components/api-authorization/AuthorizeService');

beforeAll(() => {
  jest.spyOn(AuthService, 'getUserAuthenticationStatus').mockReturnValue(
    Promise.resolve({
      isAuthenticated: true,
      user: {}
    })
  );
});

The problem here, is that when running my tests, the method keeps returning undefined rather than the mock value I had set up in my test. If we take a quick look at the exported member, we can see the class is being instantiated and then exported. Could this be the issue?

const authService = new AuthorizeService();
export default authService;
1 Answers

I think jest.mock is unnecessary here. You can simply spyOn the method since you already have an instance.

beforeAll(() => {
  jest.spyOn(authService, 'getUserAuthenticationStatus')
    // Returns promise no need to add manually
    .mockResolvedValue({ isAuthenticated: true, user: {} });
});

// And make sure you clear the mocks in the end. 
afterAll(() => jest.clearAllMocks());

Note: you are spying on the authService, not the AuthService

Related