如何测试 canvas 是否填充给定颜色?

How to test if canvas is filled with given colour?

我有一个正在渲染 canvas 元素的 React 组件。 在这个组件里面我有这个方法:

  renderCanvas(canvas) {
    canvas.fillStyle = this.props.given_colour;
    canvas.fillRect(0, 0, 800, 800);
  }

...用于创建彩色图层

所以我测试了在我的组件中调用函数和道具,它们工作正常,但现在我想要一个场景来检查上面的方法是否使用了正确的颜色。

为了进行测试,我将 jest 与酶和 sinon 一起使用。 我准备了这个场景:

it("calls to fill canvas with the given colour", () => {
    const canvasSpy = sinon.spy();
    const component = mount(<MyCanvas given_colour="#0000FF" />);

    component.instance().renderCanvas(canvasSpy);
    sinon.assert.calledWith(canvasSpy, "fillStyle");
    sinon.assert.calledWith(canvasSpy, "#0000FF");
    sinon.restore();
  });

但我得到 TypeError: canvas.fillRect is not a function

我不知道为什么会这样,我也不确定我对这种情况的总体处理方法。

我的期望是有一个场景会告诉我我的组件,在这个特定的方法中,正在使用给定的颜色。但我不知道如何实现这一目标。 我是一名 Rails 开发人员,我是 React 的新手。拜托,有人可以指出我在这个测试中做错了什么吗?

renderCanvas 期望 canvas 是一个具有方法的对象,而它是一个函数。断言是错误的,因为 canvasSpy 被断言用 fillStyle 调用,而事实并非如此。

可能应该是:

const canvasMock = { fillRect: sinon.spy() };
component.instance().renderCanvas(canvasMock);
expect(canvasMock.fillStyle).to.be("#0000FF");
sinon.assert.calledWith(canvasMock.fillRect, 0, 0, 800, 800);