在每次测试中更改URL的超级测试 [英] supertest changing url at every test

查看:62
本文介绍了在每次测试中更改URL的超级测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是后端开发的新手,我遇到一个我不理解的问题.

I'm new to backend development and i face a problem that i don't understand.

我设置了称为健康"的API的第一条路由,该路由仅返回一条简单消息以了解我的服务器是否已启动.

I set up the 1st route of my API called "health" who just return a simple message to know if my server is up.

这条路线看起来像预期的那样.

This route looks to works as expected.

但是,

当我尝试使用以下方法中的"toMatchSnapshot"方法测试此路由时开玩笑的API,由于网址中的不断变化,因此测试未通过.

when I try to test this route with the method "toMatchSnapshot" from jest API, the test is not passing because of the in the url is changing constantly.

我的测试文件"index.test.ts":

My test file "index.test.ts":

const request = supertest.agent(app);
describe("app", () => {

  it("should return a successful response for GET /health", async () => {
    const res = await request.get("/health");
    res.header = omit(res.header, ["date"]);
    expect(res).toMatchSnapshot();
  });

});

服务器"index.ts"的索引:

index of the server "index.ts":

const app = express();

expressService(app);

if (require.main === module) {
  app.listen(PORT, () => {
    console.log("server started at http://localhost:" + PORT);
  });
}

export default app;

我的函数"expressService":

my function "expressService":

const expressService = (app: Application) => {
    app.use(cors());
    app.use(express.urlencoded({ extended: true }));
    app.use(express.json());

    app.use(api);
};

export default expressService;

我的PORT变量: PORT = 3000;

-     "url": "http://127.0.0.1:49694/health",
+     "url": "http://127.0.0.1:52568/health",

这是测试失败的地方.

谢谢您的回答.

推荐答案

supertest 的文档说:

您可以将http.Server或Function传递给request()-如果服务器尚未在侦听连接,则它将绑定到临时端口,因此无需跟踪端口./p>

You may pass an http.Server, or a Function to request() - if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports.

您需要将Node.js http.Server 对象传递给 supertest.agent(),然后才能使用特定的 PORT 进行测试.

You need to pass a Node.js http.Server object to supertest.agent(), then you can use the specific PORT for testing.

这是解决方案:

index.ts :

import express from 'express';
import expressService from './expressService';
import http from 'http';

const app = express();
const PORT = process.env.PORT || 3000;

expressService(app);

function createHttpServer() {
  const httpServer: http.Server = app.listen(PORT, () => {
    console.log('server started at http://localhost:' + PORT);
  });

  return httpServer;
}

if (require.main === module) {
  createHttpServer();
}

export default createHttpServer;

expressService.ts :

import { Application } from 'express-serve-static-core';
import express, { Router } from 'express';
import cors from 'cors';

const expressService = (app: Application) => {
  app.use(cors());
  app.use(express.urlencoded({ extended: true }));
  app.use(express.json());

  const api = Router();

  api.get('/health', (req, res) => {
    res.sendStatus(200);
  });

  app.use(api);
};

export default expressService;

index.spec.ts :

import createHttpServer from './';
import { agent } from 'supertest';
import { omit } from 'lodash';

const httpServer = createHttpServer();
const request = agent(httpServer);

afterAll(done => {
  httpServer.close(done);
});

describe('app', () => {
  it('should return a successful response for GET /health', async () => {
    const res = await request.get('/health');
    res.header = omit(res.header, ['date']);
    expect(res).toMatchSnapshot();
  });
});

单元测试结果:

 PASS  src/stackoverflow/57409561/index.spec.ts (7.853s)
  app
    ✓ should return a successful response for GET /health (61ms)

  console.log src/stackoverflow/57409561/index.ts:12
    server started at http://localhost:3000

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total
Time:        8.66s

快照:

// Jest Snapshot v1

exports[`app should return a successful response for GET /health 1`] = `
Object {
  "header": Object {
    "access-control-allow-origin": "*",
    "connection": "close",
    "content-length": "2",
    "content-type": "text/plain; charset=utf-8",
    "etag": "W/\\"2-nOO9QiTIwXgNtWtBJezz8kv3SLc\\"",
    "x-powered-by": "Express",
  },
  "req": Object {
    "data": undefined,
    "headers": Object {
      "user-agent": "node-superagent/3.8.3",
    },
    "method": "GET",
    "url": "http://127.0.0.1:3000/health",
  },
  "status": 200,
  "text": "OK",
}
`;

这是完整的演示: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57409561

这篇关于在每次测试中更改URL的超级测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆