我写错了 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?
通过这两个代码示例,它可以通过两种方式获知:
- 通过查看回调的
length
属性,在第一种情况下为1
,在第二种情况下为0
。函数的长度
是它的arity(它声明的形式参数的数量¹)。 - 通过使用
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/