【问题标题】:Test async onload handler with Mocha/Chai/Sinon使用 Mocha/Chai/Sinon 测试异步 onload 处理程序
【发布时间】:2018-09-03 00:47:53
【问题描述】:

我正在尝试为应该在 image.onload 之后调用的函数添加测试。
我在 RenderObject 构造函数中附加了处理程序,该构造函数在加载时设置具有该图像源的对象的所有尺寸。
代码在我运行时按预期工作,但我未能创建成功证明这一点的测试。

import { assert, expect } from "chai";
import "mocha";
import * as Sinon from "sinon";
import { IRenderObect } from "../interfaces/IRenderObject";
import { Point } from "./Point";
import { RenderObject } from "./RenderObject";

const imageSrc = "../../images/test80x100.png";
const initialPosition = new Point(10, 20);
const objectList = RenderObject.getObjectList();

afterEach(done => {
  objectList.forEach(o => o.destroy());
  done();
});

describe("RenderObject", () => {
  it("When a new image is loaded setDimensionsForImage is called", () => {
    const spy = Sinon.spy(RenderObject.setDimensionsForImage);
    const renderObject = { imageSrc: "xxx", initialPosition };
    const object = new RenderObject(renderObject);

    assert.ok(spy.calledOnce); // Fails as it should be async
  });

  it("Object has correct dimensions for image", done => {
    const spy = Sinon.spy(RenderObject.setDimensionsForImage);
    const renderObject = { imageSrc, initialPosition };
    const object = new RenderObject(renderObject);

    window.setTimeout(() => {
      try {
        expect(object.width).to.equal(80); // Also fails...
        expect(object.height).to.equal(100);
      } finally {
        done();
      }
    }, 1000);
  });

  it("Add new objects to the object list", () => {
    const renderObject = { imageSrc, initialPosition };
    const object = new RenderObject(renderObject);

    expect(objectList.length).to.equal(1);
  });

  it("Remove objects from the object list once destroyed", () => {
    const renderObject = { imageSrc, initialPosition };
    const object = new RenderObject(renderObject);
    object.destroy();

    expect(objectList.length).to.equal(0);
  });
});

如何在图片加载后测试尺寸是否正确应用?

编辑:
我认为我的测试设置无法加载图像。我想我需要设置使用 Chrome 无头...

【问题讨论】:

  • 难道你没有一些可以处理的事件,所以你不必猜测setTimeout
  • @H.B.我刚刚记录了对构造函数和 setDimensionsForImage 的调用。第二个从未被调用,所以我认为问题出在我的测试环境中。我想我必须先将 Chrome 无头设置为环境。

标签: typescript mocha.js sinon chai


【解决方案1】:

当然,setTimeout 不是窗口对象的成员,在箭头函数内部,传递给描述回调的对象是this。你没有收到错误吗? 你可以试试这样,

it("Object has correct dimensions for image", done => {

}).timeout(()=>{

}, 1000)

【讨论】:

  • setTimeout 是窗口的属性,但我不想要它。我想测试 Image.onload 处理程序
  • 你能发布渲染对象代码吗?由于您的测试存在,您只需调用构造函数 const object = new RenderObject(renderObject);这显然不能从其中调用任何方法,因此除非 getobjectlist 方法正在调用 setDimensionsForImage() 方法,否则 spy.callonce 测试将永远不会通过。 sinon.spy 需要第一个参数作为模块/对象,第二个参数是要监视的方法名称,作为字符串。所以,如果你发布代码,我可以测试它。
猜你喜欢
  • 2021-03-14
  • 2021-10-03
  • 2018-02-13
  • 2015-12-01
  • 2018-04-08
  • 2018-03-06
  • 2023-04-11
  • 2017-06-20
  • 1970-01-01
相关资源
最近更新 更多