Testing ExpressJS endpoint with Jest

我是研究僧i 提交于 2019-12-24 08:25:50

问题


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




回答2:


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.



来源:https://stackoverflow.com/questions/45212843/testing-expressjs-endpoint-with-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!