javascript - supertest az URL-t minden tesztnél megváltoztatja
Újonc vagyok a backend fejlesztésben, és szembesültem egy problémával, amit nem értek.
Beállítottam az API-m első útvonalát, amit "health"-nek hívok, ami csak egy egyszerű üzenetet ad vissza, hogy megtudjam, működik-e a szerverem.
Ez az útvonal úgy tűnik, hogy a vártnak megfelelően működik.
Azonban,
Amikor megpróbálom tesztelni ezt az útvonalat a Jest API "toMatchSnapshot" metódusával, a teszt nem megy át, mert az URL folyamatosan változik.
A teszt fájlom, "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();
});
});
a szerver "index.ts" indexe:
const app = express();
expressService(app);
if (require.main === module) {
app.listen(PORT, () => {
console.log("server started at http://localhost:" + PORT);
});
}
export default app;
az én függvényem „expressService”:
const expressService = (app: Application) => {
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(api);
};
export default expressService;
Az én PORT változóm: PORT=3000;
- "url": "http://127.0.0.1:49694/health",
+ "url": "http://127.0.0.1:52568/health",
itt ez az, ahol a teszt hibát jelez.
Köszönöm a válaszaidat.
Válasz #1
supertest dokumentációja azt mondja:
Átadhatsz egy http.Server-t, vagy egy Függvényt a request()-nek - ha a szerver még nem figyel a kapcsolatokra, akkor egy ephemer porthoz lesz hozzárendelve helyetted, így nincs szükség a portok nyomon követésére.
A supertest.agent()-nek egy Node.js http.Server objektumot kell átadnod, majd ezután használhatod a konkrét PORT-ot a teszteléshez.
Íme a megoldás:
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();
});
});
Egységteszt eredménye:
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
Pillanatkép :
// 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",
}
`;
Itt van a kész demó: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57409561
Válasz #2
Elég egyszerű megoldás:
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/
