Duarte Castanho
Duarte Castanho

Reputation: 315

Jest mock function not working as expected

I'm trying to create a mock for a function createClient where it should return a specific object.

However, for some reason the mock is ignored and it runs the function instead of receiving the mock value.

authorization.js

// some requires here

const createClient = req => {
  if (!(req.user && req.user.access_token)) {
    throw new Error('Not authorized');
  }
  ...
  return { ... }
}

const getUser = async client => { ... }

module.exports = options => {
  ...
  createClient(req) is called here
  ...
}

authorization.test.js

import authorization from '../../server/middlewares/authorization';

describe('authorization.js', () => {
   it('Should do something', async done => {

    authorization.createClient = jest.fn(() => ({
        client: 'test',
    }));

    // ACT
    const authorizationMiddleware = authorization();
    const result = await authorizationMiddleware(someOptions);

    // ASSERT
    expect(result).toBe('authorized');
    done();
});

The error

It seems that the mock for createClient is not working as I wanted to be. It should return the object { client: 'test' }

Upvotes: 0

Views: 5066

Answers (1)

Lin Du
Lin Du

Reputation: 102547

Your code is incomplete, so I try to give a demo for your case. If you want to mock a private variable in the module scope, the createClient function for your case. You can use rewire package to do that.

E.g.

authorization.js

let createClient = (req) => {
  if (!(req.user && req.user.access_token)) {
    throw new Error('Not authorized');
  }
  function getUser() {
    return 'real user';
  }
  return { getUser };
};

const getUser = async (client) => {
  return client.getUser();
};

module.exports = (options) => {
  const client = createClient(options.req);
  return () => getUser(client);
};

authorization.test.js:

const rewire = require('rewire');

describe('61076881', () => {
  it('should get user', async () => {
    const authorization = rewire('./authorization');
    const mClient = { getUser: jest.fn().mockReturnValueOnce('fake user') };
    const mCreateClient = jest.fn(() => mClient);
    authorization.__set__('createClient', mCreateClient);
    const options = { req: { user: { access_token: '123' } } };
    const authorizationMiddleware = authorization(options);
    const user = await authorizationMiddleware();
    expect(user).toEqual('fake user');
    expect(mCreateClient).toBeCalledWith(options.req);
    expect(mClient.getUser).toBeCalledTimes(1);
  });
});

unit test results:

 PASS  stackoverflow/61076881/authorization.test.js (7.601s)
  61076881
    ✓ should get user (10ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.54s, estimated 9s

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61076881

Upvotes: 1

Related Questions