gpt4 book ai didi

javascript - 判断函数是否接受参数

转载 作者:行者123 更新时间:2023-11-30 11:16:58 27 4
gpt4 key购买 nike

我写错了 Jest 测试的代码。

test('init data', (done) => {
expect(services.getList).toHaveBeenCalled();
// accept done as param, but not called
});

我得到了预期的错误:

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

但是如果我删除 done 参数,则 passed:

test('init data', () => {
expect(services.getList).toHaveBeenCalled();
});

jest 如何知道 我接受了done 参数?太神奇了!

最佳答案

How does jest know that I accepted the done parameter?

通过这两个代码示例,它可以通过两种方式获知:

  1. 通过查看回调的 length 属性,在第一种情况下为 1,在第二种情况下为 0。函数的长度 是它的arity(它声明的形式参数的数量¹)。
  2. 通过使用Function#toString 并解析它提供的代码。在一般情况下,这不是您想要在生产代码中执行的操作,但对于测试工具来说绝对没问题。

例子:

function test(label, callback) {
console.log(`${label}: length: ${callback.length}`);
console.log(`${label}: toString(): ${callback.toString()}`);
}
test('init data', (done) => {
// ...
});

test('init data', () => {
// ...
});


¹ 在 JavaScript 中,它是它声明的形式参数的数量,不包括剩余参数(如果有)或从具有默认值的第一个参数开始的任何参数。

关于javascript - 判断函数是否接受参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51188599/

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