【发布时间】:2021-05-01 18:36:59
【问题描述】:
我在下面的代码中尝试对使用单例类的类变量的函数进行单元测试
单例类 a.js
class A{
constructor(){
this.flag = true;
}
setA(){
this.flag=false;
}
}
module.exports = new A(); //Singleton
使用单例类的类
import A from './a';
class B {
constructor() {}
hello() {
if (A.flag) {
console.log('1');
} else {
console.log('2');
}
}
}
b.test.js 的单元测试用例
import A from './a' //Singleton class
import B from './'
describe('Test Hello', () => {
const b= new B();
beforeEach(() => {
});
afterEach(() => {
jest.restoreAllMocks();
})
test('Test Hello', async () => {
try{
jest.spyOn(A, 'flag')
.mockResolvedValueOnce(true);
let output = b.hello();
}catch(e){
console.log('Error', e);
}
});
});
所以 b.js 中的一行,console.log(1) 没有被覆盖在覆盖率报告中。尝试了多种选择
【问题讨论】:
标签: node.js unit-testing jestjs mocking singleton