您可以使用jest.mock(moduleName, factory, options) 来执行此操作。
例如
UserService.js:
class UserService {
constructor() {
console.log('initialize UserService');
}
hello() {
console.log('user hello real implementation');
}
}
module.exports = new UserService();
AuthenticatorService.js:
const userService = require('./UserService');
class AuthenticatorService {
constructor() {
console.log('initialize AuthenticatorService');
}
hello() {
userService.hello();
}
}
module.exports = new AuthenticatorService();
AuthenticatorService.test.js:
const authenticatorService = require('./AuthenticatorService');
const userService = require('./UserService');
jest.mock('./UserService', () => {
return { hello: jest.fn() };
});
describe('62967707', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should pass', () => {
userService.hello.mockImplementationOnce(() => console.log('user hello mocked implementation'));
authenticatorService.hello();
expect(userService.hello).toBeCalledTimes(1);
});
});
单元测试结果:
PASS stackoverflow/62967707/AuthenticatorService.test.js (12.636s)
62967707
✓ should pass (11ms)
console.log
initialize AuthenticatorService
at new AuthenticatorService (stackoverflow/62967707/AuthenticatorService.js:5:13)
console.log
user hello mocked implementation
at Object.<anonymous> (stackoverflow/62967707/AuthenticatorService.test.js:13:60)
-------------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
AuthenticatorService.js | 100 | 100 | 100 | 100 |
-------------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 14.703s
从日志中可以看到,UserService 的真正构造函数不会执行。我们模拟了UserService 类实例的hello 方法。