首页 > 解决方案 > Mocha/Chai 测试返回错误消息,我找不到测试它的方法

问题描述

标题说明了一切,它返回类似这样的消息 Error: startDate is a required field I try to use equal, instanceof。

describe('filter', () => {
      it('needs to return a startDate required message', async () => {
          let dto = {
            'endDate': '2000-02-02',
          };
          let result = await service.filter(dto);
          expect(result).to.throw();
        };
      });

标签: node.jsmocha.jschai

解决方案


这里的问题是您没有测试错误。

想一想:当你这样做expect(result).to.throw();的时候,错误已经被抛出。

result没有抛出任何错误。

所以你可以测试调用函数时抛出的错误。

您可以按照以下方式使用chai 进行操作:

service.filter(dto).should.be.rejected;

另外,我已经使用以下代码测试了您的方法:

describe('Test', () => {
  it('Test1', async () => {
    //Only this line pass the test
    thisFunctionThrowAnError().should.be.rejected;
    //This not pass
    let result = await thisFunctionThrowAnError();
    expect(result).to.throw();
  });
});

async function thisFunctionThrowAnError(){
  throw new Error("Can mocha get this error?")
}

推荐阅读