如何模拟作为参数传递的回调的调用?

时间:2020-04-29 14:49:54

标签: javascript typescript mocking jestjs

我想知道如何模拟作为参数传递的回调的调用:

type YesOrNoHandler = (yesOrNo: boolean) => void
type CheckValue = (val: string, handler: YesOrNoHandler)

在此示例中,我要模拟代表回调的参数handler: YesOrNoHandler的调用。

const check = jest.fn().mockImplementation((_, handler) => {
   handler(true) // how to call `handler` outside of this scope ?
})

实际上,我什至不确定我是否必须为此开玩笑。有没有人知道如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

只需将handler分配给外部定义的变量。

例如

describe('61504714', () => {
  it('should pass', () => {
    let handlerRef;
    const check = jest.fn().mockImplementation((_, handler) => {
      console.log('call check');
      handlerRef = handler;
    });
    const callback = jest.fn((yesOrNo: boolean) => (yesOrNo ? 'yes' : 'no'));
    check('_', callback);
    expect(callback).not.toBeCalled();
    const rval = handlerRef(true);
    expect(rval).toBe('yes');
    expect(check).toBeCalledWith('_', callback);
    expect(callback).toBeCalledWith(true);
  });
});

测试结果:

 PASS  stackoverflow/61504714/index.test.ts (11.463s)
  61504714
    ✓ should pass (33ms)

  console.log stackoverflow/61504714/index.test.ts:5
    call check

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.581s