Javascript承诺:测试错误方案

时间:2020-03-26 13:34:15

标签: javascript unit-testing asynchronous es6-promise

我如何测试因错误而拒绝的承诺? (这是预期的行为)

我不知道为什么这个测试失败了。我正在捕获被拒绝的错误,并且测试仍然失败。根据{{​​3}}提供的示例,此方法应该有效,并且无法弄清楚它应该如何实现。这两个控制台日志都会出现。

    it('shows that even an error occurs the test passes', (done) => {
      const promise = new Promise((resolve, reject) => {
        console.log('error promise is called');
        setTimeout(() => {
          reject(new Error('dummy error thrown'));
        }, 100);
      })

      promise.then(() => {});

      promise.catch((e) => {
        console.log('error caught');
        done();
      });
    });
1) promise behaviour in tests (async) -  base test cases shows that even an error occurs the test passes:
     Uncaught Error: dummy error thrown
      at Timeout.setTimeout [as _onTimeout] (test\promise-spec.js:24:17)

这样尝试,仍然失败

      promise
        .then(() => {})
        .catch((e) => {
          console.log('error caught');
          done();
        });

1 个答案:

答案 0 :(得分:0)

原来是因为之前的测试没有完成,并且抛出错误杀死了该测试