Reputation: 5039
I'm trying to test errors throwing.
Here's my code
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');
},
};
Here is my test
const userTemplate = {
id: 1,
email: '[email protected]',
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"
),
);
});
});
the output
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)
Upvotes: 0
Views: 156
Reputation: 32158
You should pass to assert.throws
a reference to a function that when called throws an error
e.g.
const thisIsAFunctionThatIsSupposedToThrowWhenCalled = () =>
userObjectFactory(
userWithUndefinedProperty,
new Error("One of passed properties is empty") // also tried "Error" and "Error('One of passed properties is empty')" without the "new"
);
assert.throws(thisIsAFunctionThatIsSupposedToThrowWhenCalled);
or
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"
)
)
Upvotes: 1