Node.js 如何使用环回使用Mocha测试正确的数据验证?
我正在为已经存在的代码设置测试。我想测试为对象创建数据库条目的过程,特别是在给定不正确的参数时create()-方法的行为。当试图使用故意不正确的参数创建对象时,Loopback upsert()-方法(我们的create()-方法使用)在我断言该行为之前抛出一个错误 我们使用Node、Express和Loopback作为后端,使用Mocha和Chai作为测试套件。我们在对象的模型中使用环回选项“validateUpsert:true”,这可能导致抛出上述错误 基本模型如下所示:Node.js 如何使用环回使用Mocha测试正确的数据验证?,node.js,validation,testing,mocha.js,loopback,Node.js,Validation,Testing,Mocha.js,Loopback,我正在为已经存在的代码设置测试。我想测试为对象创建数据库条目的过程,特别是在给定不正确的参数时create()-方法的行为。当试图使用故意不正确的参数创建对象时,Loopback upsert()-方法(我们的create()-方法使用)在我断言该行为之前抛出一个错误 我们使用Node、Express和Loopback作为后端,使用Mocha和Chai作为测试套件。我们在对象的模型中使用环回选项“validateUpsert:true”,这可能导致抛出上述错误 基本模型如下所示: { "na
{
"name": "Field",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"numberOfSpots": {
"type": "number",
"required": true
}
}
ERROR (ValidationError/3844 on M): The instance `Field` is not valid. Details: `numberOfSpots` can't be blank (value: NaN).
所以我在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
-对象后调用此环回方法:
FieldModel.upsertWithWhere(where, Field)
.catch(error => logger.error(error))
.finally(return null);
FieldModel.upsertWithWhere(where, Field)
.catch(error => logger.error(error))
.finally(return null);
现在我希望断言可以运行,但实际上从未执行过。finally块似乎也没有执行。控制台记录如下内容:
{
"name": "Field",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"numberOfSpots": {
"type": "number",
"required": true
}
}
ERROR (ValidationError/3844 on M): The instance `Field` is not valid. Details: `numberOfSpots` can't be blank (value: NaN).
现在测试失败,尽管行为正确,即未创建对象。我需要找到一种方法来检查对象是否(正确地)没有创建,这应该通过测试来反映。谢谢
Field.create(givenFieldData)
基本上是在将givenFieldData
转换为Field
-对象后调用此环回方法:
FieldModel.upsertWithWhere(where, Field)
.catch(error => logger.error(error))
.finally(return null);
FieldModel.upsertWithWhere(where, Field)
.catch(error => logger.error(error))
.finally(return null);
第一个问题是在字段中。创建方法,它可以有效地丢弃错误并将其转换为成功结果
发生错误时,您的catch
回调将其打印到控制台,并隐式返回undefined
。因此,外部承诺最终返回到undefined
始终忽略从finally
回调返回的值。看
就个人而言,我不会试图处理create
方法中的错误,而将错误处理留给调用方
类字段{
创建(){
返回字段model.upsertWithWhere(where,字段);
}
}
然后在测试中,您应该验证create
是否返回了一个最终被预期错误拒绝的承诺。例如,使用:
it('输入错误数据时应返回null',async()=>{
//给定
常量给定字段数据={
numberOfSpots:'two'//使用文本而不是数字
}
Field.create(givenFieldData).should.be.rejectedWith(
/`numberOfSpots`不能为空/
);
});
如果您希望放弃错误并返回null
,则可以实现字段。创建如下:
类字段{
异步创建(){
试一试{
return wait FieldModel.upsertWithWhere(where,Field);
}捕捉(错误){
如果(err.name!=='ValidationError'){
//重新抛出非验证错误
//(例如,无法连接到数据库)
犯错误;
}
记录器错误(error);
返回null;
}
}
}