javascript - Mocha 测试 - 无法通过使用 async/await 拒绝承诺的测试
问题描述
使用 mocha 和 chai,我试图通过我的第二个测试以获得被拒绝的承诺,但我得到了这个错误Error: the string "error" was thrown, throw an Error
。
function fn(arg) {
return new Promise((resolve, reject) => {
if (arg) {
resolve('success')
} else {
reject('error')
}
})
}
describe('Interpreting status', function() {
it('should return the promise without error', async function(){
const arg = true
expect(await fn(arg)).to.equal('success')
});
it('should return the promise with an error', async function(){
const arg = false
expect(await fn(arg)).to.be.rejectedWith('error')
});
});
解决方案
这对我来说非常有效,
const chai = require('chai');
const expect = chai.expect;
chai.use(require('chai-as-promised'));
function fn(arg) {
return new Promise((resolve, reject) => {
if (arg) {
resolve('success');
} else {
reject(new Error('error'));
}
});
}
describe('Interpreting status', function () {
it('should return the promise without error', async function () {
const arg = true;
expect(await fn(arg)).to.equal('success');
});
it('should return the promise with an error', async function () {
const arg = false;
await expect(fn(arg)).to.be.rejectedWith(Error);
});
});
第二次测试的问题是,当你这样做时,你await fn(arg)
会得到一个错误,而不是你所期望的被拒绝的承诺。
因此,您会看到消息Error: the string "error" was thrown, throw an Error :)
记住,如果您await
在一个拒绝的承诺上将抛出一个错误,该错误必须使用try...catch
.
所以,如果你想测试,rejectedWith
那么不要使用async/await
.
此外,每当你执行 Promise 拒绝时,你应该拒绝错误,而不是字符串。我已将拒绝值更改为new Error('error')
并且我断言错误类型为rejectedWith
如果您严格按照用例进行,这应该适用于第二次测试,
it('should return the promise with an error', async function () {
const arg = false;
try {
await fn(arg);
expect.fail();
} catch (error) {
expect(error).to.equal('error');
}
});
推荐阅读
- sceneform - 如何在 Android 上将 .hdr 文件读取到图像数组?
- csv - Snowflake COPY INTO 从舞台丢失行
- svg - 将 SVG 线从直线变形为展开
- android - Android - 使用 espresso 启动片段传递导航参数
- html - Angular HTML 模板中 typescript 父级或其子类的参考
- linux - bash 模式替换在终端上工作但在脚本中不工作
- python - 如何在 Django 上更改第三方应用程序的名称?
- flutter - Flutter 键盘使 textField 隐藏
- swiftui - Swiftui NavigationLink 未执行
- terraform - AWS - 为项目设置全球预算?