javascript - 在 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
});
});
我怎样才能实现我的目标?
解决方案
尝试使用spyOn
:
const mockDoSomething = jest.spyOn(Apple.prototype, 'doSomething').mockReturnValueOnce((flag) => {
// mock do something;
})
推荐阅读
- reactjs - 何我在反应 js 中摆脱了这个错误
- c# - C# WinAppCalculator 到 Azure 中的 WebAppCalculator
- r - 将列表列表分组为R中的集合
- azure - Azure 表单识别器的准确性较低,需要更多时间
- kubernetes - 在 GCP K8s 上清除 Celery 任务
- angular - 为什么我的 ModuleFederation-Shell 不能正确加载我的微前端?
- excel - 使用带有 VBA 错误的 Selenium ChromeDriver
- jquery - 仅在 Firefox 浏览器中获取随机弹出消息
- c++ - 如何将压缩的 DDS 格式纹理与 mip 映射一起使用?
- flask - 烧瓶登录: User.is_anonymous() 是一个函数,但 current_user.is_anonymous 是一个属性。为什么?