Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom message to Jest expect?

Image following test case:

it('valid emails checks', () => {   ['[email protected]', '[email protected]'/*, ...*/].map(mail => {     expect(isValid(mail)).toBe(true);   }); }); 

I would like to add auto-generated message for each email like Email '[email protected]' 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.

like image 467
Jurosh Avatar asked Jul 27 '17 10:07

Jurosh


People also ask

What is expect in Jest?

When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things. For additional Jest matchers maintained by the Jest Community check out jest-extended .

What is expect assertions in Jest?

expect. assertions(number) will verify that a certain number of assertions are called during a test. Often, this is useful when testing asynchronous code, so as to make sure that assertions in a callback actually got called.

How do you expect a function to be called in Jest?

To check if a function was called correctly with Jest we use the expect() function with specific matcher methods to create an assertion. We can use the toHaveBeenCalledWith() matcher method to assert the arguments the mocked function has been called with.

What is Tohavebeencalled in Jest?

Jest function toHaveBeenCalledWith to ignore object order. 3. Jest to match every object in array.


1 Answers

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); }); 
like image 199
Alexey Volkov Avatar answered Oct 09 '22 03:10

Alexey Volkov