繁体   English   中英

在 Jest 中测试嵌套的 function

[英]Testing nested function in Jest

我有file.js代码,我以这种方式简化:

function Apple(,data) {
  this.attr1 = data.attr1,
  this.attr2 = data.attr2,
  this.doSomething(data.flag);
}

Apple.prototype = new function() {
  this.function1 = function() {
    // do something
  }
  this.doSomething = function(flag) {
    // return value
  }
}

我想测试function1() ,为此,我想先模拟doSomething()以返回特定值,但我失败了,因为对Apple() function 的任何调用都会立即执行doSomething()

describe('Apple', () => {
    test('test function1()', () => {
        Apple.doSomething = jest.fn().mockImplementation((2) => {
            // do something;
        });

        let apple = new Apple(data); // the original doSomething() executes here instead of the mocked version
    });
});

我怎样才能实现我的目标?

尝试使用spyOn

const mockDoSomething = jest.spyOn(Apple.prototype, 'doSomething').mockReturnValueOnce((flag) => {
    // mock do something;
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM