我有一个函数(在node.js中),该函数调用另一个setTimeout函数。而且我需要用茉莉花测试,如果调用了setTimeout函数,但是我现在不该怎么做
我希望用茉莉花测试对setTimeout函数的调用
const genOfGrid = (ctx, grid) => {
ctx.clearRect(0, 0, fieldSize, fieldSize);
drawGrid(ctx, grid);
const gridOfNextGeneration = NextGeneration(grid);
//These is the function i want to test
setTimeout(() => {
requestAnimationFrame(() => genOfGrid(ctx, gridOfNextGeneration));
}, 1000 / 10);
};
//These is the test implementation but It doesn't work
describe("Test settTimeout in genOfGrid", function() {
let timerCallback;
beforeEach(function() {
timerCallback = jasmine.createSpy("timerCallback");
jasmine.clock().install();
});
afterEach(function() {
jasmine.clock().uninstall();
});
fit("causes a timeout to be called synchronously", function() {
setTimeout(function() {
timerCallback();
}, 100);
expect(timerCallback).toHaveBeenCalled();
});
});
答案 0 :(得分:0)
不确定是否对您有帮助,但是如果您要测试生成器genOfGrid
,可以尝试以下方法:
// we need all those dependencies as injections so we can mock them
const genOfGridFactory = (drawGrid, NextGeneration, fieldSize, requestAnimationFrame) => (ctx, grid) => {
ctx.clearRect(0, 0, fieldSize, fieldSize);
drawGrid(ctx, grid);
const gridOfNextGeneration = NextGeneration(grid);
//These is the function i want to test
setTimeout(() => {
requestAnimationFrame(() => genOfGrid(ctx, gridOfNextGeneration));
}, 1000 / 10);
};
it('causes a timeout to be called synchronously', () => {
const requestAnimationFrameMock = jasmine.createSpy('requestAnimationFrame').and.callFake((cb) => cb()); // instant execution
const genOfGrid = genOfGridFactory(
drawGridStub,
NextGenerationMock,
fieldSizeStub,
requestAnimationFrameMock
)// setup them as you wish
const spy = spyOn(genOfGrid);
const ctxStub = ...;
genOfGrid(ctxStub, gridStub, NextGenerationMock);
jasmine.clock().tick(1000/10);// progress enough time to trigger setTimeout requestAnimationFrameMock will trigger its interior immediately
expect(spy).toHaveBeenCalledWith(ctxStub, NextGenerationMock(gridStub));
});