Saya baru dalam pengembangan backend dan saya menghadapi masalah yang tidak saya mengerti.

Saya mengatur rute pertama API saya yang disebut "kesehatan" yang baru saja mengembalikan pesan sederhana untuk mengetahui apakah server saya sudah aktif.

Rute ini terlihat berfungsi seperti yang diharapkan.

Namun,

Ketika saya mencoba untuk menguji rute ini dengan metode "toMatchSnapshot" dari jest API, tes tidak lulus karena url di dalam berubah terus-menerus.

File pengujian saya "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();
  });

});

Indeks 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;

Fungsi saya "expressService":

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

    app.use(api);
};

export default expressService;

Variabel PORT saya: PORT = 3000;

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

Ini adalah di mana tes gagal.

Terima kasih atas jawaban Anda.

1
Sinane 8 Agustus 2019, 12:37

2 jawaban

Jawaban Terbaik

Dokumen supertest mengatakan:

Anda dapat meneruskan http.Server, atau Fungsi ke request() - jika server belum mendengarkan koneksi maka itu terikat ke port sementara untuk Anda sehingga tidak perlu melacak port.

Anda harus meneruskan objek http.Server Node.js ke supertest.agent(), lalu Anda dapat menggunakan PORT spesifik untuk pengujian.

Inilah solusinya:

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

Hasil tes satuan:

 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

Foto:

// 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",
}
`;

Ini demo yang sudah selesai: https://github.com/ mrdulin/jest-codelab/tree/master/src/stackoverflow/57409561

3
slideshowp2 24 September 2019, 07:34

Solusi yang cukup sederhana:

const request = require('supertest'); // npm i -ED supertest
const app = require('../app'); // your expressjs app
const { url } = request(app).get('/'); // next, just use url
console.debug(url); // prints: http://127.0.0.1:57516/
0
Maksim Kostromin 17 Desember 2020, 01:21