【问题标题】:Testing ExpressJS endpoint with Jest使用 Jest 测试 ExpressJS 端点
【发布时间】:2017-12-26 00:58:27
【问题描述】:

我正在尝试使用 Jest 从我的 express 应用程序中测试一个端点。我正在从 Mocha 迁移以尝试 Jest 以提高速度。但是,我的 Jest 测试没有关闭?我很茫然……

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

【问题讨论】:

    标签: express testing tdd jestjs


    【解决方案1】:

    所以对于这次失败,我唯一能想到的就是你可能缺少包babel-preset-env

    无论如何还有另外两种使用超测的方法:

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

    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 是一个花哨的解决方案,但也是一个有更多要求的解决方案。如果您设法找到问题所在,请告诉我:)。

    (我的回答参考:http://www.albertgao.xyz/2017/05/24/how-to-test-expressjs-with-jest-and-supertest/

    【讨论】:

    • 很遗憾没有。它仍然没有退出。我认为这个问题与关闭与猫鼬的连接有关?
    • 你为什么不模拟猫鼬电话?,你可以用 jest.mock('mongoose', () => ({ themethodyouuse: jest.fn() })) const mongoose = require( '猫鼬')
    【解决方案2】:
    it("should serve the apple-app-site-association file /assetlinks.json GET", async () => {
      await request
        .get("/apple-app-site-association")
        .send()
        .expect(200);
    });
    

    如果您的配置设置正确,则此代码应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2019-10-26
      • 2020-06-14
      相关资源
      最近更新 更多