【发布时间】:2020-06-07 15:51:57
【问题描述】:
我正在尝试测试抛出的错误。
这是我的代码
const validatorMethod = (data) => {
const validationResult = Object.keys(data)
.map((key) => {
if (!data[key] || data[key].trim() === '') {
return key;
}
return true;
});
if (validationResult.filter((prop) => prop === true).length !== data.length) {
return validationResult.filter((prop) => prop !== true);
}
return true;
};
module.exports = {
userObjectFactory (data) {
console.log(data);
const invalidKeys = validatorMethod(data);
if (invalidKeys.length === true) {
console.log(1);
return data;
}
console.log(2);
throw new Error('One of passed properties is empty');
},
};
这是我的测试
const userTemplate = {
id: 1,
email: 'a@a.a',
password: 'zaq1@WSX',
fullName: 'full name',
location: 'location',
isLookingForWork: false,
};
describe('factory should throw error on undefined, null, or ""', () => {
it('should throw an error if some inputs are undefined', () => {
const userWithUndefinedProperty = userTemplate;
userWithUndefinedProperty.id = undefined;
userWithUndefinedProperty.password = undefined;
assert.throws(
userObjectFactory(
userWithUndefinedProperty, new Error('One of passed properties is empty'), // also tried "Error" and "Error('One of passed properties is empty')" without the "new"
),
);
});
});
输出
0 passing (68ms)
2 failing
1) testing UserObjectFactory
should return an object with correct data:
Error: One of passed properties is empty
at userObjectFactory (src\user\UserObjectFactory.js:2:1646)
at Context.it (test\user\UserObjectFactory.test.js:33:18)
2) testing UserObjectFactory
factory should throw error on undefined, null, or ""
should throw an error if some inputs are undefined:
Error: One of passed properties is empty
at userObjectFactory (src\user\UserObjectFactory.js:2:1646)
at Context.it (test\user\UserObjectFactory.test.js:26:9)
【问题讨论】:
-
结果如何?一些事情: 1. 您通常需要将可调用传递给检查错误的方法;和 2. 您将错误作为第二个参数传递给工厂,而不是
.throws。 -
1.你是什么意思? 2、你说的对,谢谢,但是改这个并没有解决问题
-
阅读文档:nodejs.org/api/…。您需要传递一些应该在调用时 引发错误的东西,推迟执行,否则在调用
assert.throws之前 会引发错误。同样,您发布的内容的结果是什么? -
@jonrsharpe 我在我的代码中发现了许多小错误,并且正在修复它们,但它仍然会抛出错误,因此它应该将其断言为 true。我正在添加输出
-
@jonrsharpe 如果我需要将值传递到方法中,我如何在不调用它的情况下传递它?
标签: javascript node.js unit-testing mocha.js chai