错误:<toHaveBeenCalled>:预期有间谍,但得到了 Function

Joh*_*ohn 5 javascript jasmine

这是测试代码

var list = new List([1, 2, 3, 4]);
var list2 = new List([5, 1]);

beforeAll(function () {
  spyOn(list.values, 'map').and.callThrough();

  list.map(plusOne);
});

it('Array.prototype.map()', function () {
  expect(list.values.map).not.toHaveBeenCalled();
});

This results in the following error 1) List must not call native Array function Array.prototype.map()   Message:
    Error: <toHaveBeenCalled> : Expected a spy, but got Function.
    Usage: expect(<spyObj>).toHaveBeenCalled()

  class List {
    constructor(clist = []) {
        this.values = clist;
    }
    map(f) {
        var temp = [];
        this.values.forEach((item, index) => {
                   temp.push(f(item));
                });
        this.values = temp;
        return this;
    }
}
module.exports = { List };
Run Code Online (Sandbox Code Playgroud)

我不认为这是单元测试失败,因为无论我调用 not.tohaveBeenCalled() 还是 toHaveBeenCalled(),我都会收到相同的消息。

我正在使用节点 8.9.4 和 jasmine 2.8.0。

我相信语法是正确的,因为当我针对这些测试运行其他代码时,它们会通过。但我的代码导致了这个错误。

我的问题是上面的错误是什么意思?问候,

kim*_*y82 4

我刚刚运行以下测试,它可以在 jasmine@3.0.0 上运行

fit('Spy on map works', () => {
        let someArray = [1, 3, 5];
        spyOn(someArray, 'map').and.callThrough();
        someArray.map(function(r){ console.log(r); });
        expect(someArray.map).toHaveBeenCalled();
 });
Run Code Online (Sandbox Code Playgroud)

您可能想运行此示例以了解它在您的测试中是否有效。

正如我在评论中所说,您的列表映射方法会使用新数组覆盖 list.values 。因此,间谍已经不存在了。尝试类似的东西:

someArray.forEach((item, index) => {
                   someArray[index] = f(item);
});
Run Code Online (Sandbox Code Playgroud)

解释一下发生了什么:

//WORKS
 fit('Spy on map works', () => {
    let someArray = [1, 3, 5];
    spyOn(someArray, 'map').and.callThrough();
    someArray.forEach((item, index) => {
        someArray[index] = (item + '_t');
    });
    someArray.map(function(r){ console.log(r); });
    expect(someArray.map).toHaveBeenCalled();
});
//FAILS because array is another object.
fit('Spy on map fails', () => {
    let someArray = [1, 3, 5];
    spyOn(someArray, 'map').and.callThrough();

    let tempArray = [];
    someArray.forEach((item, index) => {
        tempArray.push(item + '_t');
    });
    someArray = tempArray;

    someArray.map(function(r){ console.log(r); });
    expect(someArray.map).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)

然而,你可以只监视原型。像这样的东西:

 spyOn(Array.prototype, 'map').and.callThrough();
Run Code Online (Sandbox Code Playgroud)

然后,你的测试应该可以工作。