-
Notifications
You must be signed in to change notification settings - Fork 759
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add async/await examples to documentation #659
Comments
Something like this make jest complains. describe('/iam/users (GET)', () => {
test('Return 403 if the user is not authenticated', async () => {
expect.assertions(1)
const response = await request(server)
.get('/iam/users')
.set('x-tenant', '1')
expect(response.status).toBe(404)
})
}) Jest has detected the following 1 open handle potentially keeping Jest from exiting:
● TCPSERVERWRAP
37 | expect.assertions(1)
38 | const response = await request(server)
> 39 | .get('/iam/users')
| ^
40 | .set('x-tenant', '1')
41 |
42 | expect(response.status).toBe(404)
at Test.Object.<anonymous>.Test.serverAddress (node_modules/supertest/lib/test.js:59:33)
at new Test (node_modules/supertest/lib/test.js:36:12)
at Object.obj.<computed> [as get] (node_modules/supertest/index.js:25:14)
at Object.<anonymous> (test/user.e2e-spec.ts:39:18) |
This is a pretty big problem! A lot of people use Jest with SuperTest. But currently Jest's |
This is not because you're asing async/await, it's because you're not closing server after test finishes. Do it like that: let server: Server;
beforeEach(() => {
server = app.listen();
});
afterEach(() => {
server.close();
}); |
there's a real issue here that can be easily addressed in the documentation... here's how I understood supertest worked in trying it for the first time: import express from 'express'
import request from 'supertest'
describe('foo', () => {
const app = express()
it('bar', async () => {
const resp = await request(app).post('/').send()
expect(resp.status).toStrictEqual(200)
}
} Turns out, what I actually needed to do with my tests were this: import express from 'express'
import request from 'supertest'
describe('foo', () => {
const app = express()
const server = app.listen()
afterAll(async () => { server.close() })
it('bar', async () => {
const resp = await request(server).post('/').send()
expect(resp.status).toStrictEqual(200)
}
} While SuperTest /appears/ to work while passing in the express app, passing in the server returned by the app.listen() method (rather than the app itself) looks to be the /right/ way. Does this analysis ring true to anyone else? |
I didn't realize until after using this library for a few days that
supertest.Test
(the return value for.get
,.expect
etc) extendsPromise<Response>
after a few generations of inheritance.This means that you can do the following:
One key thing to note is that
.end
should NOT be called when usingasync/await
The text was updated successfully, but these errors were encountered: