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.
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:
Could instead become
You try this one: https://github.com/mattphillips/jest-expect-message
Just had to deal with this myself I think I'll make a PR to it possibly: But this could work with whatever you'd like. Basically, you make a custom method that allows the curried function to have a custom message as a third parameter.
It's important to remember that expect will set your first parameter (the one that goes into
expect(akaThisThing)
as the first parameter of your custom function.You can rewrite the
expect
assertion to usetoThrow()
ornot.toThrow()
. Then throw an Error with your custom text.jest
will include the custom text in the output.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:And then you use it like this:
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.You can use try-catch: