您可以使用proxyquire 模拟具有testClass 的模块。
例如
TestClass.js:
class TestClass {
constructor() {
this.method();
}
method() {
console.log('call method');
}
}
module.exports = TestClass;
然后,我们在某处需要并使用TestClass。 index.js:
const TestClass = require('./TestClass');
function main() {
return new TestClass();
}
module.exports = main;
index.test.js:
const proxyquire = require('proxyquire');
describe('61277026', () => {
it('should call original TestClass', () => {
const TestClass = require('./TestClass');
const logSpy = spyOn(console, 'log').and.callThrough();
const main = require('./');
const actual = main();
expect(actual).toBeInstanceOf(TestClass);
expect(logSpy).toHaveBeenCalledWith('call method');
});
it('should call mocked TestClass', () => {
const testClassInstance = jasmine.createSpy('testClassInstance');
const TestClassSpy = jasmine.createSpy('TestClass').and.callFake(() => testClassInstance);
const main = proxyquire('./', {
'./TestClass': TestClassSpy,
});
const actual = main();
expect(actual).toBe(testClassInstance);
expect(TestClassSpy).toHaveBeenCalledTimes(1);
});
});
带有覆盖率报告的单元结果:
Randomized with seed 34204
Started
(node:79855) ExperimentalWarning: The fs.promises API is experimental
call method
..
2 specs, 0 failures
Finished in 0.018 seconds
Randomized with seed 34204 (jasmine --random=true --seed=34204)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
TestClass.js | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
index.test.js | 100 | 100 | 100 | 100 |
---------------|---------|----------|---------|---------|-------------------