这是测试代码
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 };
我不认为这是一个单元测试失败,因为无论我调用 not.tohaveBeenCalled() 还是 toHaveBeenCalled(),我都会收到相同的消息。
我正在使用 node 8.9.4 和 jasmine 2.8.0。
我相信语法是正确的,因为当我针对这些测试运行其他代码时,他们通过了。但是我的代码导致了这个错误。
我的问题是上面的错误是什么意思? 问候,
最佳答案
我只是运行以下测试,它在 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();
});
您可能想运行此示例以了解它是否适用于您的测试。
正如我在评论中所说,您的列表映射方法使用新数组覆盖了 list.values。因此, spy 不再存在。尝试类似的东西:
someArray.forEach((item, index) => {
someArray[index] = f(item);
});
解释发生了什么:
//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();
});
但是,您可以只监视原型(prototype)。类似的东西:
spyOn(Array.prototype, 'map').and.callThrough();
然后,您的测试应该会成功。
关于javascript - 错误 : <toHaveBeenCalled> : Expected a spy, 但得到了功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48883794/