【问题标题】:How to simulate calls of a callback passed as parameter?如何模拟作为参数传递的回调调用?
【发布时间】:2020-04-30 11:02:59
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript typescript mocking jestjs


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2012-04-30
      • 2022-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多