Chai Spies语法疑问:回调函数调用次数测试始终失败
问题
我在使用Chai Spies时遇到语法问题,无法理解其使用逻辑。我编写了一个模拟array.map方法的myMap函数,代码如下:
function myMap(inputArray, callback) { let newArr = []; for (i = 0; i < inputArray.length; i++) { let nEl = callback(inputArray[i]); newArr.push(nEl); }; return newArr; } module.exports = myMap;
同时编写了对应的测试代码:
const chai = require('chai'); const expect = chai.expect; const spies = require('chai-spies'); chai.use(spies); const myMap = require('../problems/my-map'); describe('function myMap', function () { const arr = [1, 2, 3]; const cb1 = el => el*2; it('should return new array passed through callback', function () { expect(myMap(arr, cb1)).to.deep.equal([2, 4, 6]); }); it('should preserve original array', function () { expect(arr).to.deep.equal([1,2,3]); }); it('see if .map used on array', function () { expect(chai.spy.on(arr, 'map')).to.not.have.been.called(); }); it('callback called array.length times', function () { let spy1 = chai.spy(cb1); expect(spy1).to.have.been.called.exactly(arr.length); }) });
其中第3个测试(检测是否使用数组的map方法)能够正常工作,但第4个测试(验证回调函数被调用次数等于数组长度)始终显示调用次数为0,与预期的3次不符。我目前使用的是降级后的Chai 4.3.0版本,因存在ES6冲突暂未解决。请问该如何修正这个测试用例?
解决方案
问题核心是你创建了回调的spy包装,但没有将这个spy传入myMap函数——你仍在使用原始的cb1,导致spy从未被触发,调用次数自然为0。
修正步骤:
- 创建spy包装后的回调函数
- 将该spy作为参数传入
myMap并执行函数 - 最后断言spy的调用次数
修正后的第4个测试用例代码:
it('callback called array.length times', function () { // 用spy包装原始回调 let spy1 = chai.spy(cb1); // 把spy传给myMap并执行,触发回调调用 myMap(arr, spy1); // 断言调用次数等于数组长度 expect(spy1).to.have.been.called.exactly(arr.length); })
额外提示:你的myMap函数中for循环的i未声明,会成为全局变量,建议添加let声明:
for (let i = 0; i < inputArray.length; i++) { let nEl = callback(inputArray[i]); newArr.push(nEl); }
内容的提问来源于stack exchange,提问作者Rossi
相关产品推荐
相关产品推荐

