jest:Promise丢失了错误信息

时间:2017-11-16 08:52:57

标签: javascript es6-promise jestjs

修改:这与此处描述的问题相同:https://github.com/facebook/jest/issues/2980。由于错误而未调用done(),因此达到了jamsin超时。没关系。但是不好的是,jasmin / jest应该报告错误的错误。

注意:可以找到示例源代码 here

考虑以下函数,它创建一个Promise并调用 承诺解决后的done回调:

// file: foo.js

function foo(done) {
    const p = new Promise((resolve, reject) => {
        setTimeout(() => {
            //const xxx = 2;
            resolve(xxx);
        }, 100);
    });
    p.then(data => {
        console.log(data);
        done()
    })
}

exports.foo = foo;

它包含错误:未定义xxx变量,因此必须输入错误 提高。

如果我运行导入此函数并在脚本中执行它:

// file: index.js

const foo = require('./foo').foo;

foo(() => {});

并使用node v8.6.0运行脚本:

node index.js

我收到了预期的错误(ReferenceError: xxx is not defined):

/home/dfroger/repo/dfroger/issue/jest-promise-error/foo.js:5
            resolve(xxx);
                    ^

ReferenceError: xxx is not defined
    at Timeout.setTimeout [as _onTimeout] (/home/dfroger/repo/dfroger/issue/jest-promise-error/foo.js:5:21)
    at ontimeout (timers.js:469:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:264:5)

如果现在我为foo编写单元测试:

// file: foo.test.js

const foo = require('./foo').foo

describe('async', () => {
    it('run foo', done => {
        foo(done);
    });
});

使用jest v21.2.1

运行它
./node_modules/.bin/jest

我不再收到有关xxx being not defined的错误消息:

  async
    ✕ run foo (5004ms)

  ● async › run foo

    Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

      at node_modules/jest-jasmine2/build/queue_runner.js:64:21
      at ontimeout (timers.js:469:11)
      at tryOnTimeout (timers.js:304:5)
      at Timer.listOnTimeout (timers.js:264:5)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        5.574s, estimated 6s
Ran all test suites.

我错过了使用jest吗?它是jest错误吗?我怎样才能确保jest 始终正确报告错误消息?

1 个答案:

答案 0 :(得分:0)

你没有为你的承诺添加一个阻止块;虽然我无法全面测试,但我相信这是你的问题;

// file:foo.js

function foo(done) {
    const p = new Promise((resolve, reject) => {
        setTimeout(() => {
            //const xxx = 2;
            resolve(xxx);
        }, 100);
    });
    p.then(data => {
        console.log(data);
        done()
    })
    .catch(err => {
        console.log(`Following error occured : ${err}`);
  });    
}

exports.foo = foo;