调用jest模拟函数时执行回调

时间:2018-06-14 13:55:15

标签: javascript unit-testing testing jestjs

我有这个测试:

describe("onAfterSwipe", () => {
  it("Should call a handler after swiping", async () => {
    const onAfterSwipe = jest.fn();
    const wrapper = mount(
      <Swipeable onAfterSwipe={onAfterSwipe}>Hello</Swipeable>
    );

    swipe(wrapper, 500);

    await wait(600);

    expect(onAfterSwipe).toHaveBeenCalledTimes(1);
  });
});

我等待600毫秒来检查函数是否被调用(在动画结束后调用onAfterSwipe),我想做类似的事情:

describe("onAfterSwipe", () => {
  it("Should call a handler after swiping", (done) => {
    const onAfterSwipe = jest.fn();
    const wrapper = mount(
      <Swipeable onAfterSwipe={onAfterSwipe}>Hello</Swipeable>
    );

    swipe(wrapper, 500);

    onAfterSwipe.called((args) => {
      expect(onAfterSwipe).toHaveBeenCalledWith("right");
      done();
    })
  });
});

1 个答案:

答案 0 :(得分:0)

我不熟悉 jest ,但是从documentation我认为你可以这样做:

const onAfterSwipe = jest.fn(args => {
   // expect args to be "right"
   done();
});