首页 文章

异步Mocha测试(使用Chai断言库)应该失败,但标记为传递

提问于
浏览
2

我在TypeScript中使用mocha测试框架和chai断言库编写了一些测试(我对其中的所有3个都是新的),并且发现错误被抛出并且在下面的代码中调用了assert.fail() . 但是,测试仍然标记为通过 . 我很困惑为什么会发生这种情况,如果我对承诺做错了 . 此外,如下所示,还有一个UnhandledPromiseRejectionWarning . 我不明白为什么这被标记为未处理,因为我已经包含了一个catch块 . 对于如何解决这个问题,我将不胜感激,谢谢!

User.all()
      .then((users) => {
        expect(users.length).to.equal(0);
        return User.create('test@test.email', '12345', 'test', true, true);
      })
      .then(() => {
        return User.all();
      })
      .then((users) => {
        expect(users.length).to.equal(1);
      })
      .catch((error) => {
        assert.fail();
      });

调试控制台

✓ should create a new record
  with existing e-mail in the database
(node:29903) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): AssertionError: assert.fail()
(node:29903) 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.

Code

Debug Console

1 回答

  • 5

    正如Benjamin Gruenbaum上面所说,这是通过确保it块返回一个承诺来解决的

    it('should create a new record', () => {
    
       return User.all()
          .then((users) => {
            expect(users.length).to.equal(0);
            return User.create('test@test.email', '12345', 'test', true, true);
          })
          .then(() => {
            return User.all();
          })
          .then((users) => {
            expect(users.length).to.equal(1);
          })
         .catch((error) => {
           assert.fail();
         });
     });
    

相关问题