Alex Chin
Alex Chin

Reputation: 1642

Testing ExpressJS endpoint with Jest

I'm trying to test an endpoint from my express application using Jest. I'm migrating from Mocha to try out Jest to improve the speed. However, my Jest test does not close? I'm at a loss...

process.env.NODE_ENV = 'test';
const app = require('../../../index');
const request = require('supertest')(app);

it('should serve the apple-app-site-association file /assetlinks.json GET', async () => {
  const response = await request.get('/apple-app-site-association')
  expect(response.statusCode).toBe(200);
});

Upvotes: 1

Views: 2677

Answers (2)

Yilmaz
Yilmaz

Reputation: 49182

it("should serve the apple-app-site-association file /assetlinks.json GET", async () => {
  await request
    .get("/apple-app-site-association")
    .send()
    .expect(200);
});

if your configuration setup is correct this code should work.

Upvotes: 0

Alvaro Lorente
Alvaro Lorente

Reputation: 3084

So the only thing I could think for this failing is that you might be missing the package babel-preset-env.

In any case there are two other ways to use supertest:

it('should serve the apple-app-site-association file /assetlinks.json GET', () => {
  return request.get('/apple-app-site-association').expect(200)
})

or

it('should serve the apple-app-site-association file /assetlinks.json GET', () => {
    request.get('/apple-app-site-association').then(() => {
        expect(response.statusCode).toBe(200);
        done()
    })
})

async is the fancy solution, but is also the one that has more requirements. If you manage to find what was the issue let me know :).

(Reference for my answer: http://www.albertgao.xyz/2017/05/24/how-to-test-expressjs-with-jest-and-supertest/)

Upvotes: 1

Related Questions