Вот решение для юнит-тестирования:
closures.js
:
function closures() {
this.after = (r, cb) => {
counter = 1;
return () => {
if (counter == r) cb();
};
};
}
module.exports = closures;
closures.test.js
:
const closures = require('./closures');
fdescribe('Closure', () => {
let closure;
const hello = () => console.log('hello');
beforeEach(() => {
closure = new closures();
});
describe('after', () => {
beforeEach(() => {
spyOn(console, 'log');
});
it('executes callback after called first x times', () => {
const runOnce = closure.after(1, hello);
const first = runOnce();
expect(first).toEqual(undefined);
expect(console.log).toHaveBeenCalledWith('hello');
expect(console.log.calls.count()).toEqual(1);
});
it('should not call calback if counter is not equal with r', () => {
const runOnce = closure.after(2, hello);
const first = runOnce();
expect(first).toEqual(undefined);
expect(console.log).not.toHaveBeenCalled();
});
});
});
Результаты юнит-теста с отчетом о покрытии:
HeadlessChrome 73.0.3683 (Mac OS X 10.13.6): Executed 2 of 5 (skipped 3) SUCCESS (0.04 secs / 0.004 secs)
TOTAL: 2 SUCCESS
TOTAL: 2 SUCCESS
TOTAL: 2 SUCCESS
src/stackoverflow/59790114 | 100 | 100 | 100 | 100 | |
closures.js | 100 | 100 | 100 | 100 | |
closures.test.js | 100 | 100 | 100 | 100 | |