Jasmine在全局窗口对象上创建本地JS函数的Spy

Jasmine Create Spy on Native JS Function on Global Window Object

本文关键字:JS 函数 Spy 创建 全局 窗口 对象 Jasmine      更新时间:2023-09-26

我正在编写一个测试,看看是否调用了Array.prototype.map。我认为这会起作用,因为Array.prototype.map位于全局窗口对象上:

    it("does not use Array.prototype.map", function(){
        spyOn(window, "Array.prototype.map")
        fn([2,2,3]);
        expect(Array.prototype.map.calls.count()).toEqual(0);
    });

我收到错误Array.prototype.map does not exist。当我创建自己的自定义全局函数时,这种方法可以很好地工作。基于这篇文章,似乎任何全局函数都可以使用我上面使用的语法进行窥探。如果我创建自己的函数,这种语法就会起作用。关于为什么Array.prototype.map返回undefined,有什么想法吗?

希望你已经得到了答案,但对于搜索的人来说,这是因为你应该

spyOn(Array.prototype, 'map');