【问题标题】:Test with UnhandledPromiseRejectionWarning but passing使用 UnhandledPromiseRejectionWarning 进行测试但通过
【发布时间】:2020-09-30 07:33:06
【问题描述】:

我正在测试 xml2js 是否返回与预期相同的 JS。如果我在期望值等于接收到的值时运行代码,则不会出现错误。但是,如果我在存在差异时运行代码,我会得到:

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.199 s, estimated 8 s
Ran all test suites matching /create/i.
  console.error
    expect(received).resolves.toEqual(expected) // deep equality

所以控制台能够告诉我有什么问题,但测试套件认为一切正常。

      it('converts xml to JS', async () => {
     try {
        fs.readFile(__dirname + '/' + bpmnxml, 'utf8', async (err, data) => {
           if (err) {
              console.error(err);
           } else {
              try {
                 await expect(parseXML(data)).resolves.toEqual(bpmnjson);
              } catch (errExpect) {
                 console.error(errExpect.message);
                 // eslint-disable-next-line jest/no-try-expect
                 // return expect(errExpect).toEqual(new Error('error on expect'));
              }
           }
        });
     } catch (errReadFile) {
        console.error(errReadFile);
     }
  });

如果我取消注释 // return expect(errExpect).toEqual(new Error('error on expect'));,则会收到另一个错误:

(node:28424) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:28424) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

但测试套件仍然说它通过了。

我可以做些什么来强制错误(这样我得到一个测试失败)但我没有得到这个UnhandledPromiseRejectionWarning? try-catch 块没有处理这个问题。

【问题讨论】:

    标签: typescript async-await jestjs expected-exception


    【解决方案1】:

    它可能与 fs.readFile 相关,因为它的同步版本适用于我:

       it('converts xml to JS', async () => {
          const data = fs.readFileSync(__dirname + '/' + bpmnxml, 'utf8');
          expect.hasAssertions();
          await expect(parseXML(data)).resolves.toEqual(bpmnjson);
       });
    

    什么时候应该相等:

        √ converts xml to JS (16 ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        3.069 s, estimated 4 s
    

    当我对其中一个进行随机更改时:

    Test Suites: 1 failed, 1 total
    Tests:       1 failed, 1 total
    Snapshots:   0 total
    Time:        3.247 s, estimated 4 s
    

    【讨论】:

      猜你喜欢
      • 2017-02-04
      • 2019-03-29
      • 2019-02-15
      • 2017-09-21
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多