【发布时间】:2021-04-22 13:07:16
【问题描述】:
嗨,我有 2 个类 A 类和 B 类,A 类构造函数在构造函数中实例化 B 类
A类有方法hello,B类有方法bye, A类方法你好调用B类方法再见, 在我的代码覆盖范围内,b 类方法 bye 无法返回 null
模拟了 b 类
在 a.js 中
import b from './b';
class A {
//Main class from which other class is instantiated in constructor
constructor() {
this.b = new b();
}
hello() {
let someval = this.b.bye(); //want to mock this bye function with null value
if (someval) {
console.log('success');
} else {
console.log('error'); // this line code coverage is not happening
}
}
}
在./b
class B {
bye() {
//want to mock this method to return null
console.log('Actual method call');
}
}
在 a.test.js 中
import a from './a';
import b from './b';
jest.mock('./b', () => {
return jest.fn().mockImplementation(() => {
return {
bye: () => {
return null;
},
};
});
});
describe('Test A Hello', () => {
const a = new a();
beforeEach(() => {
// Clear all instances and calls to constructor and all methods:
});
afterEach(() => {
jest.restoreAllMocks();
});
test('Get Token-Negative', async () => {
a.hello();
});
});
预期结果是 Class a 将调用 hello,它将调用 Class b 的 bye,并且由于它被模拟为 null 它将返回 null,但模拟的 bye 方法没有被调用
【问题讨论】:
标签: javascript unit-testing testing jestjs mocking