node.js - 使用 Chai.throw 异步捕获复杂的 Mongoose 错误
问题描述
Chai.throw
用于针对他们的message
道具测试简单的错误。在简单的错误情况下,这可以正常工作。
it.only('Should catch a thrown message', () => {
function throwSomething() {
throw new Error('something')
}
expect(throwSomething).to.throw('something')
})
但是,在针对失败的 Mongoose 验证进行异步测试时,我发现我无法访问嵌套的错误消息。我原本想用 try+catch 来使用异步测试,但是expect
catch 块内的调用不能保证运行,在这种情况下,当测试实际上没有出错时,测试可能会通过。
it.only('Errors on save if username is not unique', async () => {
// setup original user
const original = new UserModel(testParams)
await original.save()
try {
// try to create a new user with the same username
const duplicate = new UserModel({
username: testParams.username,
email: 'test_other@mail.com',
password: testParams.password
})
// save the user that has a non-unique username
await duplicate.save()
} catch (err) {
// confirm the nested error was as expected
expect(err.errors.username.message).to.equal(
'Error, expected `username` to be unique. Value: ' +
'`' + testParams.username + '`'
)
}
})
如果我要调用expect(duplicate.save).to.throw('...')
它,它不会检查我想要的错误字段。
另一种选择是,我不是异步测试我的模型,而是使用 Promise 回调,并在回调done()
内部.catch()
调用。但是,如果我正在测试许多嵌套的 Promise 操作,我发现这种方法是不可取的。
有没有办法用来Chai.throw
捕获 Mongoose 产生的复杂嵌套错误?
解决方案
推荐阅读
- python - 优先考虑来自 csv 的重复项
- linux - 两个默认网关上的路由问题
- reporting-services - 从 Reporting Services 迁移到 SSDT
- kubernetes - Kubernetes 不创建证书
- .net - 不同的 RedirectURL Google OAuth
- react-native - 更改 FlatList 的唯一 onPressed 项的样式
- c# - RabbitMQ.Fakes 单元测试 C#,System.TypeLoadException
- scala - [RollOverStatus] = 'Y' then 'Yes' Else 'No' end as RollOverStatus 如何在 spark-scala 2.4.0 中编写
- asp.net - 当用户在请求期间强制退出浏览器时,w3wp 的 CPU 使用率突然升高
- javascript - 什么语法错误导致函数的“文本”在这个 JS 闭包中返回,而不是让它递增?