简体   繁体   English

对于从 ES6 文件导出的单个 function,在 Angular 中使用 Jest 监视方法调用的正确方法是什么?

[英]What is the proper way to spy on a method call using Jest in Angular for a single exported function from an ES6 file?

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);
 }
}

What I've tried我试过的

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);
 }
}
___

What I end up with when I debug is that I can see that my debugger is getting into the actual method itself, which is fine because I expect jest to call the actual implementation for the spy.当我调试时,我最终得到的结果是我可以看到我的调试器正在进入实际方法本身,这很好,因为我希望 jest 调用间谍的实际实现。 However I get a 'Expected: my assertation , 'calls: 0'但是我得到一个'预期:我的断言,'调用:0'

I've run myself pretty crazy and consider myself at least half decent at tests.我已经把自己逼疯了,认为自己在考试中至少有一半还算过得去。 But for the life of me when it comes to spying on exported functions that aren't injected through classes, I end up bewildered.但是对于我来说,当涉及到监视不是通过类注入的导出函数时,我最终感到困惑。

I've looked at: SpyOn individually exported ES6 functions but from my understanding it doesn't track because my example has different modules.我看过: SpyOn 单独导出的 ES6 函数,但据我了解,它没有跟踪,因为我的示例有不同的模块。 Thank you in advance for kindness in your response.预先感谢您的善意回应。

i think its better to mock the function call when testing the parent function like this:我认为在像这样测试父 function 时模拟 function 调用更好:

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);
 }
}

you can test the "doThing" function in a seperate unit test helper.spec.ts.您可以在单独的单元测试 helper.spec.ts 中测试“doThing”function。

PS.附言。 in a newer version of jest i need to use jest.spyOn(class, 'fucntion').mockImplementation.在较新版本的 jest 中,我需要使用 jest.spyOn(class, 'fucntion').mockImplementation。 In an older version i was using spyOn(class, 'function').and.stub();在旧版本中,我使用的是 spyOn(class, 'function').and.stub(); maybe because of jasmine types.可能是因为 jasmine 种类型。

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

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