【问题标题】:How to resolve promise in unit tests?如何解决单元测试中的承诺?
【发布时间】:2023-03-27 19:27:01
【问题描述】:

在我的 componentDidMount 中添加 Promise 后,测试不再通过。如何解决 componentDidMount 中的承诺?我需要类似 runOnlyPendingTimers 之类的东西,但为了 Promise。

我的测试是:

it("should clear canvas on each frame draw", () => {
    mount(<CoinsAndStars stars={true} coins={true} DeviceSupport={DeviceSupport} />);
    ctxMock.clearRect = jest.fn();
    jest.runOnlyPendingTimers();
    expect(ctxMock.clearRect).toHaveBeenCalledTimes(1);
    jest.runOnlyPendingTimers();
    expect(ctxMock.clearRect).toHaveBeenCalledTimes(2);
    jest.runOnlyPendingTimers();
    expect(ctxMock.clearRect).toHaveBeenCalledTimes(3);
});

【问题讨论】:

  • 可能欺骗here
  • 您可以将其包装在 Async/await 中,只需将其放入级联 .then 块中即可。
  • 你是什么意思?我有 .then 在我的 componentDidMount
  • @Shammoo 是这样的吗? (async function() { mount(&lt;CoinsAndStars stars={true} coins={true} DeviceSupport={DeviceSupport} /&gt;); ctxMock.clearRect = jest.fn(); jest.runOnlyPendingTimers(); expect(ctxMock.clearRect).toHaveBeenCalledTimes(1); jest.runOnlyPendingTimers(); expect(ctxMock.clearRect).toHaveBeenCalledTimes(2); jest.runOnlyPendingTimers(); expect(ctxMock.clearRect).toHaveBeenCalledTimes(3); })();
  • 前一个不会改变行为。你能分享你的cdm函数的摘录吗?你想测试什么?

标签: javascript reactjs enzyme jestjs


【解决方案1】:

也许对任何人都能派上用场。如果你在componentDidMount中使用promise,在测试中你需要等待而mount会结束

it("should clear canvas on each frame draw", async () => {
    await mount(<CoinsAndStars stars={true} coins={true} DeviceSupport={DeviceSupport} />);
    ctxMock.clearRect = jest.fn();
    jest.runOnlyPendingTimers();
    expect(ctxMock.clearRect).toHaveBeenCalledTimes(1);
    jest.runOnlyPendingTimers();
    expect(ctxMock.clearRect).toHaveBeenCalledTimes(2);
    jest.runOnlyPendingTimers();
    expect(ctxMock.clearRect).toHaveBeenCalledTimes(3);
});

【讨论】:

    猜你喜欢
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 2018-10-30
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多