我已经搜索了数天以了解如何完成此操作,但我尝试过的所有方法均无济于事。我有一个authenticate
模块,可以在其他模块之间共享,并且我想在我的单元测试中使用笑话为它创建一个模拟。这是我目前所拥有的:
authenticate.js
const got = require('got');
const authenticate = async (options) => {
let res = ...api request using got library to retrieve token...
return { data: res.access_token };
};
exports.authenticate = authenticate;
schedule.js
const schedule = async (options) {
// import authenticate library
const authenticate = require('./authenticate');
const login = await authenticate.authenticate(options);
const result;
...stuff to set result...
result = {
data: 'success'
};
return result;
};
exports.schedule = schedule;
shedule.test.js
const scheduler = require('./schedule');
test('[schedule]', async () => {
const options = {...};
jest.mock('./authenticate', () => ({
authenticate: jest.fn()
}));
const authenticate = require('./authenticate');
authenticate.authenticate.mockReturnValue({
data: mockOptions.access_token
});
const moduleUnderTest = await scheduler.schedule(options);
expect(moduleUnderTest).toEqual({ data: 'success' });
});
答案 0 :(得分:1)
您不应该在功能范围内使用jest.mock(moduleName, factory, options),应在 MODULE 范围内使用它。此外,对于您而言,我认为没有任何理由使用rewire模块。
例如
authenticate.js :
const got = require('got');
const authenticate = async (options) => {
let res = 'got';
return { data: res.access_token };
};
exports.authenticate = authenticate;
schedule.js :
const schedule = async (options) => {
const authenticate = require('./authenticate');
const login = await authenticate.authenticate(options);
const result;
result = {
data: 'success'
};
return result;
};
exports.schedule = schedule;
schedule.test.js:
const scheduler = require('./schedule');
jest.mock('./authenticate', () => ({
authenticate: jest.fn(),
}));
describe('62074254', () => {
test('[schedule]', async () => {
const authenticate = require('./authenticate');
const mockOptions = { access_token: '123' };
authenticate.authenticate.mockReturnValue({
data: mockOptions.access_token,
});
const options = {};
const moduleUnderTest = await scheduler.schedule(options);
expect(moduleUnderTest).toEqual({ data: 'success' });
expect(authenticate.authenticate).toBeCalledWith({});
});
});
带有覆盖率报告的单元测试结果:
PASS stackoverflow/62074254/schedule.test.js (10.742s)
62074254
✓ [schedule] (6ms)
-------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
schedule.js | 100 | 100 | 100 | 100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.202s