Testing ExpressJS endpoint with Jest

2019-07-14 19:15发布

问题:

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);
});

回答1:

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/)