[[oktatas:web:nodejs:rest_api|< REST API]] ====== SuperTest ====== * **Szerző:** Sallai András * Copyright (c) Sallai András, 2022 * Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]] * Web: https://szit.hu ===== Bevezetés ===== A SuperTest REST API tesztelő NodeJS könyvtár. ===== Telepítés ===== npm install supertest --save-dev ===== Próba ===== const request = require('supertest'); Futtatás: node proba.js Ha nem kapunk kimenetet, a telepítés sikeres. ===== Egyszerű GET teszt ===== const request = require('supertest'); request('http://localhost:3000') .get('/api/employees') .end(function(err, res) { if (err) throw err; console.log(res.body); }); Az end() metódus véglegesíti a kérést, az API hívásával. ===== Elvárt válaszok ===== Az expect() metódussal jelezzük, hogy az elvárt választ 200. request('http://localhost:3000') .get('/api/employees') .expect(200) .end(function(err, res) { if (err) throw err; }); Az expect() hívást az end() előtt kell megtenni. Vizsgáljuk azt is, hogy a válasz JSON volt-e. request('http://localhost:3000') .get('/api/employees') .expect(200) .expect('Content-Type', 'application/json') .end(function(err, res) { if (err) throw err; }); ===== A JSON válasz ellenőrzése ===== request('http://localhost:3000') .get('/api/employees') .expect(200) .expect('Content-Type', 'application/json') .expect(function(res) { if (!res.body.hasOwnProperty('name')) throw new Error("Expected 'name' key!"); if (!res.body.hasOwnProperty('city')) throw new Error("Expected 'city' key!"); }) .end(function(err, res) { if (err) throw err; }); Használhatunk assert() metódust, így rövidebb sorokat kapunk: const request = require('supertest'); const assert = require('assert'); request('http://localhost:3000') .get('/api/employee') .expect(200) .expect('Content-Type', 'application/json') .expect(function(res) { assert(res.body.hasOwnProperty('name')); assert(res.body.hasOwnProperty('city')); }) .end(function(err, res) { if (err) throw err; }); ===== Kombináció Mocha-val ===== describe('Dolgozók tesztje', function() { it('válasz, JSON tartalommal', function(done) { request('http://localhost:3000') .get('/api/employees') .expect(200) .expect('Content-Type', 'application/json') .expect(/{"name":".*","city":"Szeged"}/, done); }); }); Vegyük észre, hogy elhagytuk az end() metódust, és az utolsó expect() metódus végére egy done paraméter került. ===== Felhasznált webhelyek ===== * https://www.testim.io/blog/supertest-how-to-test-apis-like-a-pro/ (2022) * https://www.npmjs.com/package/supertest (2022)