首页 > 解决方案 > 在 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()函数的调用都会立即执行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
    });
});

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

标签: javascriptfunctionjestjs

解决方案


尝试使用spyOn

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

推荐阅读