0
votes

I'm trying to mock the return value (or implementation) of the functions inside another module's function with Jest. I need to test different scenarios (function throws error, returns null, returns an object, etc...)

That module (userService) returns a function that returns an object with that functions:

userService.js (I want to mock the return value of findUser & createUser)

...
function userService(userModel) {
  async function findUser(userQuery) {
    ...
    return foundUser;
  }

  async function createUser(user) {
    ...
    return createdUser;
  }

  return { findUser, createUser };
}

module.exports = userService;

And I'm testing authStravaController, which uses that service functions: authStravaController

...
const authStravaServiceRaw = require('../../services/authStravaService');
const userServiceRaw = require('../../services/userService');
const bikeServiceRaw = require('../../services/bikeService');
...

function authStravaController(userModel, bikeModel) {
  const { findUser, createUser } = userServiceRaw(userModel); <-- WANT TO MOCK THAT FUNCTIONS

  async function authStrava({ body: { authCode } }, res) {
    ...
    try {
      ...
      const findUserQuery = {
        stravaUserId: stravaBasicUser.stravaUserId,
      };
      authUser = await findUser(findUserQuery); <-- MOCK THIS FUNCTION RETURN MULTIPLE TIMES

      if (!authUser) {
        resStatus = CREATED;
        createdUser = await createUser(stravaBasicUser); <-- SAME
        ...
        createdUser.bikes = createdBikes.map((bike) => bike._id);
        createdUser.save();

        authUser = { createdUser, createdBikes };
      }

      return handleResponseSuccess(res, resStatus, authUser);
    } catch (authStravaError) {
      return handleResponseError(res, authStravaError);
    }
  }
  return { authStrava };
}

module.exports = authStravaController;

At the moment I've been able to mock the function return value just 1 time, and I can't find a way to rewrite it, so now I can only test 1 scenario

This code at the top of the file let me test 1 scenario

jest.mock('../../services/userService', () => () => ({
  findUser: jest.fn().mockReturnValue(1),
  createUser: jest.fn().mockReturnValue({ username: 'userName', save: jest.fn() }),
}));

I've tried to mock it in multiple ways and can't get it to work, how could I do it to test different return values:

  • findUser: jest.fn().mockReturnValue(1),
  • findUser: jest.fn().mockReturnValue(undefined),
  • findUser: jest.fn().mockReturnValue({user:'username'}),
  • etc...

Thanks!

1
If you just do jest.mock('../../.service/userService) and then do expect(findUser.mock).toBeTruthy(), does it pass?Shafiq Jetha
No, it throws this error: ReferenceError: findUser is not definedGerard Ramon

1 Answers

0
votes

I fixed it importing all the services outside the controller function, at the top of the file.

This way I can mock the returnValue of any function.