typescript - 在 Angular 中使用 Jest 监视来自 ES6 文件的单个导出函数的方法调用的正确方式是什么?
helpers.ts
export function doThing() {
// some stuff
}
myClass.ts
___
import { doThing } from './helpers.ts'
class myClass {
function someFunction(firstArg, secondArg) {
const thing = someThirdThing;
doThing(firstArg, secondArg, someThirdArg);
}
}
我尝试过的
myClass.spec.ts
import * as helpers from './helpers.ts'
describe('someFunction' () => {
it('calls doThing with the correct parameters', () => {
spyOn(helpers, 'doThing');
const myClass = new MyClass();
myClass.someFunction(first, second);
expect(helpers.doThing).toHaveBeenCalledWith(first, second, someThirdThing);
}
}
___
当我调试时,我的结果是我可以看到调试器确实进入了实际的方法,这没问题,因为我预计 jest 会为 spy 调用实际实现。然而我得到一个‘预期: 我的断言,调用次数: 0’
我把自己逼得够疯,自认为在测试中至少算得上还可以。但对于那些不是通过类注入的导出函数进行间谍(监测)时,我简直是无论如何也弄不明白。
我已经看过:SpyOn 对单独导出的 ES6 函数的使用,但据我理解它无法跟踪,因为我的示例有不同的模块。提前感谢您在回复中的善意。
答案#1
我认为在测试父函数时,最好像这样模拟函数调用:
describe('someFunction' () => {
it('calls doThing with the correct parameters', () => {
jest.spyOn(helpers, 'doThing').mockImplementation;
const myClass = new MyClass();
myClass.someFunction(first, second);
expect(helpers.doThing).toHaveBeenCalledWith(first, second, someThirdThing);
}
}
你可以在单独的单元测试文件 helper.spec.ts 中测试 "doThing" 函数。
附注:在更新版本的 jest 中,我需要使用 jest.spyOn(class, 'fucntion').mockImplementation。在旧版本中,我使用的是 spyOn(class, 'function').and.stub();可能是因为 jasmine 类型的原因。
