如何正确地使用Jest模拟/测试构造函数



我想测试Module2构造函数及其其他函数。在不破坏testFunc1、testFunc2以使用Jest进行测试的情况下,模拟Module2构造函数的正确方法是什么。

// ****************************************
// Module 1 component
class Module1 {
init() {
// ........
}
}
module.exports = new Module1()

// ****************************************
// Module 2 component
const module1 = require('./module1')
class Module2 {
constructor() {
try {
module1.init()
} catch (err) {
console.log('error')
process.exit(1)
}
}
testfunc1 = () => {
// ........
}
testfunc2 = () => {
// ........
}
}
module.exports = new Module2()

您正在测试module2,因此需要模拟module1而不是module2

您可以使用jest.doMock(moduleName,factory,options(来模拟module1模块。嘲笑之后,require变成了module2。此外,在使用不同的实现进行模拟之前,您应该使用jest.resetModules((从require.cache对象重置模块缓存。

例如

module1.js:

class Module1 {
init() {}
}
module.exports = new Module1();

module2.js:

const module1 = require('./module1');
class Module2 {
constructor() {
try {
module1.init();
} catch (err) {
console.log('error');
process.exit(1);
}
}
testfunc1 = () => {};
testfunc2 = () => {};
}
module.exports = new Module2();

module2.test.js:

describe('67099526', () => {
beforeEach(() => {
jest.resetModules();
});
it('should initialize module1 correctly', () => {
const module1instance = { init: jest.fn() };
jest.doMock('./module1', () => {
return module1instance;
});
require('./module2');
expect(module1instance.init).toBeCalledTimes(1);
});
it('should handle error', () => {
const exitSpy = jest.spyOn(process, 'exit').mockImplementation();
const module1instance = {
init: jest.fn().mockImplementationOnce(() => {
throw new Error('initialize module1');
}),
};
jest.doMock('./module1', () => {
return module1instance;
});
require('./module2');
expect(module1instance.init).toBeCalledTimes(1);
expect(exitSpy).toBeCalledWith(1);
});
});

单元测试结果:

PASS  examples/67099526/module2.test.js (11.508 s)
67099526
✓ should initialize module1 correctly (8819 ms)
✓ should handle error (18 ms)
console.log
error
at new Module2 (examples/67099526/module2.js:8:15)
------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |   33.33 |     100 |                   
module2.js |     100 |      100 |   33.33 |     100 |                   
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        13.743 s

最新更新