【问题标题】:Asynchronous Javascript code testing using Jest works when it is not supposed to使用 Jest 的异步 Javascript 代码测试在不应该的情况下工作
【发布时间】:2018-08-06 00:42:11
【问题描述】:

Jest 的docs 提供了一个反例,说明在测试异步代码时不应该做什么。我是这样实现的:

const expect = require('expect');

function fetchData(cb) {
    setTimeout(cb('peanut butter2'), 1500);
}

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

    fetchData(callback);
});

我跑了npx jest test.js,这是输出:

Fabians-MacBook-Pro:playground fabian$ npx jest test.js
 FAIL  ./test.js
  ✕ the data is peanut butter (6ms)

  ● the data is peanut butter

    expect(received).toBe(expected)

    Expected value to be (using Object.is):
      "peanut butter"
    Received:
      "peanut butter2"

      at callback (playground/test.js:9:22)
      at fetchData (playground/test.js:4:16)
      at Object.<anonymous>.test (playground/test.js:12:5)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.866s, estimated 1s
Ran all test suites matching /test.js/i.

我不明白结果。

  1. 为什么即使我没有调用 done(),它仍然可以工作,因为 Jest 建议您这样做来测试异步代码?我很确定 setTimeout 是异步的,因为我在一个空白测试脚本中使用 console.log() 语句对其进行了测试,第二个在第一个包含在 setTimeout 函数中之前触发。

  2. 此外,当我的超时设置为 1500 毫秒时,测试在 0.866 秒内失败。当我的回调甚至不应该被调用时,Jest 怎么会收到错误的回调数据(花生酱2)?

【问题讨论】:

    标签: javascript asynchronous testing jestjs


    【解决方案1】:

    因为您的测试看起来应该是async,但实际上是synchronous,因为您的代码中有错误。

    您有以下内容,看起来它被设计为在1500ms 之后调用方法cb但您立即调用cb

    setTimeout(cb('peanut butter2'), 1500);

    然后将string 传递给您的callback 函数,该函数立即/同步运行expect

    你可能想要的是这样的:

    setTimeout(function() { cb('peanut butter2') }, 1500);

    或者,让 setTimeout 将 arg 传递给您的 cb 函数并调用它:

    setTimeout(cb, 1500, 'peanut butter2')

    正如预期的那样,它实际上会在1500ms 之后调用您的cb 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-08
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多