gpt4 book ai didi

javascript - 如何在这些函数中测试 setTimeout?

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:49 25 4
gpt4 key购买 nike

我有一个函数(在 node.js 中)调用另一个 setTimeout 函数。我需要用 jasmine 进行测试,如果 setTimeout 函数被调用,但我现在不知道如何执行这些

我希望用 jasmine 测试对 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();
});
});

最佳答案

不确定这是否对您有帮助,但如果您想测试生成器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));
});

关于javascript - 如何在这些函数中测试 setTimeout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56464502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com