gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 20:55:15 24 4
gpt4 key购买 nike

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

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

实际上,我什至不确定是否必须使用 jest。有人知道如何实现这一目标吗?

最佳答案

只需将处理程序分配给外部定义的变量即可。

例如

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

关于javascript - 如何模拟作为参数传递的回调的调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61504714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com