I recently ran into the following testing code in an Express app using Supertest and Jest:
const supertest = require("supertest");
const app = require("../app");
const api = supertest(app);
test("notes are returned as json", async () => {
await api
.get("/api/notes")
.expect(200)
.expect("Content-Type", /application\/json/);
});
I'm kind of confused where the .expect(200)
is coming from. Is this part of Supertest? Because I know that in Jest when we call expect
we typically use a matcher like this:
expect(200).toBe(200)
But somehow this test works without having to call a matcher.
Supertest v6.3.1
.expect()
API comes from the Test
class of the supertest
package. The key code for handling .expect(200)
:
// status
if (typeof a === 'number') {
this._asserts.push(wrapAssertFn(this._assertStatus.bind(this, a)));
// body
// ...
}
The status code will be used like this:
wrapAssertFn(this._assertStatus.bind(this, 200))
See the source code
The this._asserts
array holds all the assertion. Supertest will check each assertion until finding a failed assertion here