【问题标题】:Failing chai test for async function throwing an error异步函数的 chai 测试失败并引发错误
【发布时间】:2019-07-24 04:11:38
【问题描述】:

我想测试我的“missing_body”是否被抛出。但是我的测试只显示了已经捕获的错误,但是期望测试仍然失败。你能帮我理解吗?

async add(req) {
   const db = _.get(req, 'app.locals.db');
   const bookDescription = req.body;
   logger.info('books.add', bookDescription);
   if (_.isEmpty(bookDescription)) {
     throw new Error('missing_body');
   }
   [...]
}

describe('+add(req)', function() {
    it('should fail because of missing body', async function() {
      const req = {
        body: {},
      };

      expect(await this.ctrl.add(req)).to.throw(new Error('missing_body'));
    });
});

【问题讨论】:

    标签: node.js async-await mocha.js chai


    【解决方案1】:

    另一个错误是提供一个对象方法(或任何依赖此方法的独立函数)作为断言的目标。这样做是有问题的,因为当函数被 .throw 调用时 this 上下文将会丢失;它无法知道这应该是什么。有两种方法可以解决这个问题。一种解决方案是将方法或函数调用包装在另一个函数中。另一种解决方案是使用绑定。如果你测试同步功能。

    expect(function () { cat.meow(); }).to.throw();  // Function expression
    expect(() => cat.meow()).to.throw();             // ES6 arrow function
    expect(cat.meow.bind(cat)).to.throw();           // Bind
    

    但在异步(await add()).to.throw(Error) 中永远不会工作:如果失败() 拒绝,则会抛出错误,并且永远不会执行 .to.throw(Error)。所以你需要做这样的事情:

    it('should fail', async () => {
      await expect(this.ctrl.add(req.body)).to.be.rejectedWith(Error);
    })
    

    解决方案:

    async add(req) {
      const db = _.get(req, 'app.locals.db');
      const bookDescription = req.body;
      logger.info('books.add', bookDescription);
      if (_.isEmpty(bookDescription)) {
        throw new Error('missing_body');
      }
      [...]
    }
    
    describe('+add(req)', function() {
      it('should fail because of missing body', async function() {
        const req = {
          body: {},
        };
    
      await expect(this.ctrl.add(req.body)).to.be.rejectedWith(Error);
      });
    });
    

    【讨论】:

    • 如果 _.empty 返回 true,这不是错误,这是我要检查的。所以在我的测试中,我会坚持使用this.ctrl.add(req)。我做错的是,将我的等待放在期望中,而不是在期望中。谢谢!你解决了我的问题!
    【解决方案2】:

    如果您希望捕获一些错误,则需要在 catch 块内声明。您正在尝试断言创建新错误实例的错误。如果您使用的是同步编程,那么您需要捕获您的错误,例如:

        it('should fail because of missing body', async function() {
          const req = {
            body: {},
          };
    
          try {
            await this.ctrl.add(req)
          } catch(e) {
             expect(e.message).to.equal('missing_body');
          }
        });
    

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 2015-06-02
      • 2021-11-27
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      相关资源
      最近更新 更多