angularjs - Jasmine spyOn 函数不是对象的方法

标签 angularjs unit-testing jasmine

如何监视不是对象方法的函数。在我的情况下,callMe也不在window对象上 - 它是通过 Angular 加载的依赖项。

if (X) {
  callMe('hello');
}

最佳答案

您可以使用jasmine.createSpy方法创建一个 spy 对象。鉴于 spy 对象是常规 JavaScript 对象,您可以使用此 spy 对象来覆盖您的 callMe 函数,以便监视它。

function callMe() {
    // implementation
}

describe('an example block', function() {
    it('creates a spy', function() {
        callMe = jasmine.createSpy('callMe');
        callMe();
        expect(callMe).toHaveBeenCalled();
    });
});

来自Jasmine 2.5 documentation :

When there is not a function to spy on, jasmine.createSpy can create a “bare” spy. This spy acts as any other spy – tracking calls, arguments, etc. But there is no implementation behind it. Spies are JavaScript objects and can be used as such.

关于angularjs - Jasmine spyOn 函数不是对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39298815/

相关文章:

javascript - gMarker.key 未定义,它是必需的!! Angular 和谷歌地图应用程序中的错误

c# - 为什么 Assert.AreEqual(T obj1, Tobj2) 会因相同的字节数组而失败

unit-testing - Angular 2 单元测试 : How do I test for the context menu and double click events?

javascript - Jasmine toBeCloseTo 第二个参数是什么?

angularjs - Angular JS : Access data filtered in ng-repeat (ngRepeat) from controller

javascript - Angularjs - 使用 php 上传文件

javascript - 当文本省略号应用于元素时如何使用工具提示?

javascript - 使用 Jasmine 测试 Angular 服务时,脚本的包含顺序是否导致此未知提供程序错误

javascript - Jasmine Spy 根据参数返回不同的值

具有多个请求的 Angular HttpClient 测试