node.js - 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();
};
});
解决方案
这里的问题是您没有测试错误。
想一想:当你这样做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?")
}
推荐阅读
- html - 背景图像不会出现在 CSS 中
- hive - 如何让 Dataproc 将 Python-Hive 连接检测为 Yarn Job?
- typescript - 为什么 TypeScript 中的方法链接会导致泛型类型推断失败?
- python - 如何不在 tkinter 文本小部件中选择空白文本?
- javascript - GraphQL 变异创建文档,它是对象数组
- javascript - 如何使用 prosMirror 创建可变特征
- javascript - 如何在使用 LeafletJS 单击多边形时从一个 GeoJson 图层切换到另一个图层?
- c++ - QSqlQuery 的副本共享相同的绑定值
- c# - 我想创建一个函数来获取它调用者的名称,以获取一组单选按钮 c#
- python - 将列数据分隔为实时绘图 csv 文件