When to use createSpy, createSpyObject, and spyOn?

huangapple go评论78阅读模式
英文:

When to use createSpy, createSpyObject and spyOn?

问题

我最近了解到,spyOn 不能与外部依赖项一起使用,只能与被测试的系统一起使用。

但是我有一些关于为什么不能使用它的问题,我得到的答案很少。

所以我想知道在哪些情况下应该使用它们的最佳实践。

英文:

I have learned recently that spyOn cannot be used with external dependencies and can only be used with System Under Test.

But I have some questions regarding why it cant be used and I came up with very few answers.

So I would like to know the best practices where we should use each of them.

答案1

得分: 5

jasmine.createSpy 可以在没有函数可供监视时使用。它会像 spyOn 一样跟踪调用和参数,但没有实现。

jasmine.createSpyObj 用于创建一个将会监视一个或多个方法的模拟对象。它返回一个具有每个字符串属性的对象,这些属性都是间谍。

你应该在对象上使用 spyOn 方法。spyOn 的优点是你可以调用原始方法。

英文:

jasmine.createSpy can be used when there is no function to spy on. It will track calls and arguments like a spyOn but there is no implementation.

jasmine.createSpyObj is used to create a mock that will spy on one or more methods. It returns an object that has a property for each string that is a spy.

you should have a method on the object with spyOn.The advantage of the spyOn is that you can call the original method

答案2

得分: 2

我们可以在需要监听函数时使用 jasmine.createSpy,例如:

let router = { navigate: jasmine.createSpy("navigate") }

在这里,我们使用 jasmine.createSpy 创建了一个监听函数。

jasmine.createSpyObj 用于创建具有方法的监听类/对象,例如:

let service = jasmine.createSpyObj("ApiService", ["getData"])

在这里,ApiService 是一个具有 getData 方法的类。

英文:

We can use jasmine.createSpy when we need to spy a function e.g.

     let router = { navigate: jasmine.createSpy("navigate") },

here we're creating spy function using jasmine.createSpy

jasmine.createSpyObj is used to create spy class/obj which has methods e.g.

     let service = jasmine.createSpyObj("ApiService", ["getData"])}

here ApiService is class which has getData function.

huangapple
  • 本文由 发表于 2020年1月7日 02:14:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定