Qwerty
Qwerty

Reputation: 314

How to resolve promise in unit tests?

After I added Promise in my componentDidMount tests ceased to pass. How can I resolve promise in componentDidMount? I need something like runOnlyPendingTimers but for Promise.

My test is:

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);
});

Upvotes: 1

Views: 352

Answers (1)

Qwerty
Qwerty

Reputation: 314

Maybe for anyone come in handy. If you use promise in componentDidMount, in test you need await while mount will end

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);
});

Upvotes: 1

Related Questions