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

标签 javascript node.js jasmine

我有一个函数(在 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/

相关文章:

javascript - 在 d3 树布局链接上添加标记

javascript - 如何在映射 : ReactJS 中访问正确的 'this'

javascript - MongoDB计算不同的值(value)?

javascript - 错误 : spawn EACCES in ubuntu for node. js/express 应用程序尝试运行 python

javascript - Protractor :如何检查中继器中是否完全出现一个条目

javascript - PHP飞到购物车效果jquery ajax/我想提交表单但仍然是同一页面

javascript - VSCode 仅在某处导入时通过相应的 Foo.d.ts 为 Foo.js 提供智能感知;如何在 Foo.js 本身中启用智能感知?

node.js - 如何在 Amazon Cognito 中高效获取大量用户

angularjs - 等待 Protractor 与页面同步时出错 : "[ng:test] no injector found for element argument to getTestability

javascript - 带有 Protractor 的 Jasmine 自定义匹配器,用于检查浏览器标题