Javascript 测试闭包。如何测试传递给闭包的回调

Javascript 测试闭包。如何测试传递给闭包的回调,javascript,callback,jasmine,closures,Javascript,Callback,Jasmine,Closures,在威尔·森坦斯(Will Sentance)的带领下,我正在frontendmasters.com上的一门课程中学习如何应对收尾挑战。我正在努力测试我的功能 此函数after将回调执行前需要调用的次数作为第一个参数,将回调作为第二个参数 这是我的解决办法 function closures() { // more functions above... this.after = (r, cb) => { counter = 1; return () => { i

在威尔·森坦斯(Will Sentance)的带领下,我正在frontendmasters.com上的一门课程中学习如何应对收尾挑战。我正在努力测试我的功能

此函数
after
将回调执行前需要调用的次数作为第一个参数,将回调作为第二个参数

这是我的解决办法

function closures() {
  // more functions above...
  this.after = (r, cb) => {
    counter = 1;
    return () => { if (counter == r) cb() } ;
  };
}
这是我的规格

describe("Closure", () => {
  beforeEach( () =>{
    closure = new closures();
  });

  describe('after', () => {
    beforeEach(() => {
      hello = () => console.log('hello');
      spyOn(console, 'log');
      runOnce = closure.after(3, hello);
    });

    it("executes callback after called first x times", () => {
      first = runOnce();
      second = runOnce();
      third = runOnce();
      expect(first).toEqual(undefined); //successfull
      expect(second).toEqual(undefined);  // successful
      expect(console.log).toHaveBeenCalledWith('hello');  // successful
      expect(console.log.calls.count()).toEqual(1);  // fails expected 0 to eq 1
    })
  });
}

Please advise how to test the callback is only invoked once.


以下是单元测试解决方案:

closures.js

函数闭包(){
this.after=(r,cb)=>{
计数器=1;
return()=>{
if(counter==r)cb();
};
};
}
module.exports=闭包;
closures.test.js

const closures=require('./closures');
fdescribe('Closure',()=>{
让关闭;
const hello=()=>console.log('hello');
在每个之前(()=>{
闭包=新闭包();
});
描述('after',()=>{
在每个之前(()=>{
间谍(控制台,'日志');
});
它('在第一次调用x次后执行回调',()=>{
const runOnce=closure.after(1,hello);
const first=runOnce();
expect(第一)、toEqual(未定义);
expect(console.log).toHaveBeenCalledWith('hello');
expect(console.log.calls.count()).toEqual(1);
});
它('如果计数器与r不相等,则不应调用calback',()=>{
const runOnce=closure.after(2,hello);
const first=runOnce();
expect(第一)、toEqual(未定义);
expect(console.log).not.tohavebeencall();
});
});
});
单元测试结果和覆盖率报告:

headlesschrome73.0.3683(Mac OS X 10.13.6):执行5次中的2次(跳过3次)成功(0.04秒/0.004秒)
总数:2
总数:2
总数:2
src/stackoverflow/59790114 | 100 | 100 | 100 | 100 ||
closures.js | 100 | 100 | 100 | 100 ||
closures.test.js | 100 | 100 | 100 | 100 ||

尝试直接创建间谍,而不是在控制台日志上进行间谍
jasmine.createSpy
如果
cb
不是作为
closures
函数(或者可能来自外部作用域)的参数引入的函数,那么您将无能为力。