使用Mocha / Chai / Sinon测试异步onload处理程序

时间:2018-03-24 12:58:10

标签: typescript mocha sinon chai

我正在尝试为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无头......

1 个答案:

答案 0 :(得分:0)

当然,setTimeout不是窗口对象的成员,而在箭头函数内部,传递给describe回调的对象是this。你没有收到错误吗? 您可以尝试使用它,

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

}).timeout(()=>{

}, 1000)