我正在使用嵌套的Promises在before()钩子中设置我的测试数据库。 它运行良好,但我不知道如何在最高级别(在before()钩子中)捕获错误。 查看console.log,当在嵌套的Promise中捕获错误时,它将作为值返回到上一级...不匹配..
group.test.js
before(() => {
return utils.clearCollections()
.then(() => {
return utils.createSuperAdmin()
.then(() => {
return utils.createTestGroups(3)
.then((insertedGroups) => {
groups = insertedGroups;
return utils.addRolesInGroups(groups)
.then((insertedRoles) => {
console.log('DONE ! %j', insertedRoles);
})
.catch((e) => {
console.log('error %j', e);
});
});
});
});
});
test.utility.js
export function addRolesInGroups(groups) {
...
return Role.insertMany([roleA1, roleA2, roleA3, roleB2, roleB3, roleC3, role4 ])
.then((insertedRoles) => {
console.log('Successfully created test roles in groups');
return insertedRoles;
})
.catch((e) => {
console.log('Error inserting many: %j', e);
return e;
});
}
的console.log
错误在Promise函数中被正确捕获 addRolesInGroups() 但它被返回到调用before()钩子..没有捕获......
Error inserting many: {"code":11000,"index":3,"errmsg":"E11000
duplicate key error collection: cockpit-api-test.roles index: name_1
dup key: { : \"manager\" }","op": "__v":0,
"_groupId":"5954d45e05206235d308f4d6",
"name":"manager","description":"can R group, can RW
user","_id":"5954d45e05206235d308f4db","rolePermissions"
[],"permissions":[{"resourceName":"group","authorizedActions"
["read"]},{"resourceName":"user","authorizedActions"
["read","write"]}],"users":[]}}
DONE ! {"code":11000,"index":3,"errmsg":"E11000 duplicate key error
collection: cockpit-api-test.roles index: name_1
dup key: { : \"manager\" }","op"
{"__v":0,"_groupId":"5954d45e05206235d308f4d6",
"name":"manager","description":"can R group, can RW
user","_id":"5954d45e05206235d308f4db","rolePermissions":[],
"permissions":[{"resourceName":"group","authorizedActions":["read"]}
{"resourceName":"user","authorizedActions":["read","write"]}]
,"users":[]}}
答案 0 :(得分:0)
这是因为您没有重新抛出缓存错误,而是返回了解决缓存错误的新Promise。
将return e;
更改为throw e;