开玩笑的模拟功能无法按预期运行

时间:2020-04-07 09:31:41

标签: javascript unit-testing jestjs

我正在尝试为函数createClient创建一个模拟,该模拟应返回特定对象。

但是,由于某种原因,模拟被忽略,并且它运行函数而不是接收模拟值。

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();
});

错误

似乎createClient的模拟无法正常运行。它应该返回对象{ client: 'test' }

1 个答案:

答案 0 :(得分:1)

您的代码不完整,因此我尝试为您提供一个示例。如果要在模块作用域中模拟私有变量,请根据情况使用createClient函数。您可以使用rewire软件包来做到这一点。

例如

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);
  });
});

单元测试结果:

 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

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61076881