Image following test case:
it('valid emails checks', () => {
['abc@y.com', 'a@b.nz'/*, ...*/].map(mail => {
expect(isValid(mail)).toBe(true);
});
});
I would like to add auto-generated message for each email like Email 'f@f.com' should be valid so that it's easy to find failing test cases.
Something like:
// .map(email =>
expect(isValid(email), `Email ${email} should be valid`).toBe(true);
Is it possible in Jest ?
In Chai it was possible to do with second parameter like expect(value, 'custom fail message').to.be... and in Jasmine seems like it's done with .because clause. But cannot find solution in Jest.
You try this lib that extends jest: https://github.com/mattphillips/jest-expect-message
test('returns 2 when adding 1 and 1', () => {
expect(1 + 1, 'Woah this should be 2!').toBe(3);
});
I don't think it's possible to provide a message like that. But you could define your own matcher.
For example you could create a toBeValid(validator) matcher:
expect.extend({
toBeValid(received, validator) {
if (validator(received)) {
return {
message: () => `Email ${received} should NOT be valid`,
pass: true
};
} else {
return {
message: () => `Email ${received} should be valid`,
pass: false
};
}
}
});
And then you use it like this:
expect(mail).toBeValid(isValid);
Note: toBeValid returns a message for both cases (success and failure), because it allows you to use .not. The test will fail with the corresponding message depending on whether you want it to pass the validation.
expect(mail).toBeValid(isValid);
// pass === true: Test passes
// pass === false: Failure: Email ... should be valid
expect(mail).not.toBeValid(isValid);
// pass === true: Failure: Email ... should NOT be valid
// pass === false: Test passes
Although it's not a general solution, for the common case of wanting a custom exception message to distinguish items in a loop, you can instead use Jest's test.each.
For example, your sample code:
it('valid emails checks', () => {
['abc@y.com', 'a@b.nz'/*, ...*/].map(mail => {
expect(isValid(mail)).toBe(true);
});
});
Could instead become
test.each(
['abc@y.com', 'a@b.nz'/*, ...*/],
'checks that email %s is valid',
mail => {
expect(isValid(mail)).toBe(true);
}
);