Jestjs 类方法上由其引用调用的jest.spyOn无效

Jestjs 类方法上由其引用调用的jest.spyOn无效,jestjs,Jestjs,假设我们有一个带有一些方法的类。我们想监视方法A是否被调用。这个班看起来像下面 class Parent { constructor() { this.conf = [{ id:'1', func: this.methodA.bind(this)}, { id:'2', func: this.methodB.bind(this)}] } methodA() { console.log('methodA is called from meth

假设我们有一个带有一些方法的类。我们想监视方法A是否被调用。这个班看起来像下面

class Parent {
    constructor() {
        this.conf = [{ id:'1', func: this.methodA.bind(this)}, { id:'2', func: this.methodB.bind(this)}]
    }
    methodA() {
        console.log('methodA is called from methodC');
    }
    methodB() {
        console.log('methodB is called from methodC');
    }
    methodC() {
        this.conf.forEach((eachConf) => {
            eachConf.func();
        });
    }
}
module.exports = new Parent();
在jest测试文件中,调用methodC并希望确保methodA和methodB也被调用。 testSpy.js const Parent=需要“/Parent”

it('check methodA and methodB called', async () => {
    const methodA = jest.spyOn(Parent, 'methodA');
    const methodB = jest.spyOn(Parent, 'methodB');
    Parent.methodC();
    expect(methodA).toHaveBeenCalled();
    expect(methodB).toHaveBeenCalled();
});
它说,预期mock函数已经被调用,但它没有被调用


如何使用jest处理这些类型的函数调用?

这里的问题是返回新的父函数;来自模块。这意味着在模拟methodA和methodB时已经调用了构造函数。在您调用this.methodA.bindthis的构造函数中,这意味着在列表中存储对绑定到此的原始函数的引用。在稍后的测试中,您将用mock替换methodA和methodB,但是已经很晚了,因为this.conf保存了对原始方法的引用,所以mock对列表中的方法没有影响


长话短说,最好只返回类本身,而不是它的实例

谢谢,因为它缺少模拟效果