【问题标题】:Async Mocha test (with Chai assertion library) should fail, but is marked as passing异步 Mocha 测试(使用 Chai 断言库)应该失败,但被标记为通过
【发布时间】:2017-07-18 12:01:24
【问题描述】:

我已经使用 mocha 测试框架和 chai 断言库在 TypeScript 中编写了一些测试(我对所有这 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

【问题讨论】:

  • Users.all 调用之前添加一个return
  • 谢谢!哈哈,我刚想通了,正要发帖,你抢先了。我正在阅读这篇文章 (alisdair.mcdiarmid.org/…),并阅读了“要为此编写测试,请确保您的 it 块返回一个 Promise,而 mocha 将负责其余的工作:”

标签: node.js typescript promise mocha.js chai


【解决方案1】:

正如上面的 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();
     });
 });

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 2021-12-31
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 2018-03-06
    • 1970-01-01
    • 2017-06-20
    相关资源
    最近更新 更多