我正在为现有代码设置测试。我想测试一个对象的数据库条目的创建,特别是当给定不正确参数时,create()-方法应该如何表现。当尝试使用故意不正确的参数创建对象时,环回 upsert()-方法(由我们的 create()-方法使用)在我断言行为之前抛出错误。
我们使用 Node、Express 和 Loopback 作为后端,使用 Mocha 和 Chai 作为测试套件。我们在对象的模型中使用环回选项“validateUpsert:true”,这可能会导致抛出上述错误。
基本模型看起来像这样:
{
"name": "Field",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"numberOfSpots": {
"type": "number",
"required": true
}
}
所以我在 Mocha 中的测试用例看起来像下面的代码。请注意 numberOfSpots 旁边的注释:
it('should return null upon entering false data', async() => {
// Given
const givenFieldData = {
numberOfSpots: 'two' // Using text instead of a number
}
// When
const newField = await Field.create(givenFieldData);
// Then
assert.isNull(newField);
});
Field.create(givenFieldData)
基本上是在将 givenFieldData
转换为 Field
-Object 之后调用此 Loopback 方法:
FieldModel.upsertWithWhere(where, Field)
.catch(error => logger.error(error))
.finally(return null);
现在我希望断言运行但实际上从未执行过。 finally block 似乎也没有被执行。控制台记录如下内容:
ERROR (ValidationError/3844 on M): The instance `Field` is not valid. Details: `numberOfSpots` can't be blank (value: NaN).
现在测试失败了,尽管行为是正确的,即对象没有被创建。我需要找到一种方法来检查对象是否(正确)未创建,这应该通过通过的测试反射(reflect)出来。谢谢!
最佳答案
Field.create(givenFieldData)
basically calls this Loopback method after transforminggivenFieldData
into aField
-Object:FieldModel.upsertWithWhere(where, Field) .catch(error => logger.error(error)) .finally(return null);
第一个问题出在您的 Field.create
方法中,它有效地丢弃错误并将它们转换为成功结果。
当发生错误时,您的 catch
回调会将其打印到控制台并隐式返回 undefined
。结果,外部 promise 最终返回到 undefined
。
finally
回调返回的值总是被忽略。参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally .
就个人而言,我不会尝试处理您的 create
方法中的错误并将错误处理留给调用者。
class Field {
create() {
return FieldModel.upsertWithWhere(where, Field);
}
}
然后在测试中,您应该验证 create
返回一个最终因预期错误而被拒绝的 promise 。例如,使用 should.js :
it('should return null upon entering false data', async() => {
// Given
const givenFieldData = {
numberOfSpots: 'two' // Using text instead of a number
}
Field.create(givenFieldData).should.be.rejectedWith(
/`numberOfSpots` can't be blank/
);
});
如果您希望丢弃错误并返回null
,那么您可以按如下方式实现Field.create
:
class Field {
async create() {
try {
return await FieldModel.upsertWithWhere(where, Field);
} catch(err) {
if (err.name !== 'ValidationError') {
// re-throw non-validation errors
// (e.g. cannot connect to the database)
throw err;
}
logger.error(error);
return null;
}
}
}
关于node.js - 如何使用 Loopback 使用 Mocha 测试正确的数据验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56463380/