【问题标题】:How does Jest's callback testing actually workJest 的回调测试实际上是如何工作的
【发布时间】:2017-12-22 07:35:02
【问题描述】:

当使用 Jest 测试利用回调的异步代码时,您可以输入一个 done 参数,然后在测试中调用该参数。这允许测试知道在完成测试之前等到 done() 函数被调用。例如,在包含 done() 函数的回调运行之前,此代码不会完成。

test('the data is peanut butter', done => {
  function callback(data) {
    expect(data).toBe('peanut butter');
    done();
  }

  fetchData(callback);
});

我的问题是,Jest 如何真正知道它何时需要等待 done() 调用?由于它存在的唯一其他地方是测试运行的函数的参数,Jest 是否有办法检查该函数中的参数?如果是这样,它是如何做到的?

【问题讨论】:

    标签: reactjs testing asynchronous callback jestjs


    【解决方案1】:

    一个函数有一个.length 属性,它返回为其声明的参数的数量:

    function test0() {}
    function test1(arg0) {}
    function test2(arg0, arg1) {}
    
    console.log( test0.length ); // 0
    console.log( test1.length ); // 1
    console.log( test2.length ); // 2
    

    这就是 Jest 知道您的测试处理程序需要一个 done 回调的方式,它会假设测试是异步的。

    【讨论】:

    • 谢谢!这就说得通了。 :)
    猜你喜欢
    • 2021-06-16
    • 2016-10-05
    • 1970-01-01
    • 2021-01-21
    • 2011-09-27
    • 2021-12-16
    • 2013-03-14
    • 2021-03-23
    • 2011-02-11
    相关资源
    最近更新 更多