I'm using Supertest and Jest to test a Node.js API.
A sample test has the following format
it('Read a note for a user', (done) => {
request(graphqlURL)
.post('/graphql')
.set(baseHeaders())
.send({
query: graphQLQuery
})
.end((err, res) => {
expect(res.status).toBe(200);
done();
})
});
Currently when the expectation fails, the following gets logged
expect(received).toBe(expected) // Object.is equality
Expected: 200
Received: 404
I'd also like to log the request and the response alongside the failed tests to have more context while debugging.
Is there a way to print those as well, only for the tests which are failing?
expect
works by throwing an Error
when an expectation fails.
The message
property of the Error
is what gets printed in the test report.
I suppose if you want to use an existing expectation and just want to augment the fail message with additional data you can catch the Error
, append your additional data to the message
property, then throw the Error
again like this:
it('Read a note for a user', (done) => {
request(graphqlURL)
.post('/graphql')
.set(baseHeaders())
.send({
query: graphQLQuery
})
.end((err, res) => {
try {
expect(res.status).toBe(200);
} catch (err) {
// --- add additional data to the error message here ---
err.message = `${err.message}\n\nfailing query: ${graphQLQuery}`;
throw err; // throw the error so test fails as expected
}
done();
})
});