[英]determine whether the function accepts parameters
我为错误测试编写了错误的代码。
test('init data', (done) => {
expect(services.getList).toHaveBeenCalled();
// accept done as param, but not called
});
我收到了预期的错误:
超时 - 在jest.setTimeout指定的5000ms超时内未调用异步回调。
但如果我删除done
参数,则传递 :
test('init data', () => {
expect(services.getList).toHaveBeenCalled();
});
jest如何知道我接受了done
参数? 这太神奇了!
jest
如何知道我接受了done参数?
有了这两个代码示例,它有两种方式可以知道:
length
属性,在第一种情况下为1
,在第二种情况下为0
。 函数的length
是它的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中,它声明的形式参数的数量不包括rest参数(如果有),或者第一个参数中的任何参数,默认值为向前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.