Felhasználói eszközök

Eszközök a webhelyen


oktatas:web:nodejs:rest_api:supertest

< REST API

SuperTest

Bevezetés

A SuperTest REST API tesztelő NodeJS könyvtár.

Telepítés

npm install supertest --save-dev

Próba

proba.js
const request = require('supertest');

Futtatás:

node proba.js

Ha nem kapunk kimenetet, a telepítés sikeres.

Egyszerű GET teszt

gettest.js
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.

extest.js
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.

extest.js
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

extest.js
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:

extest.js
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

moctest.js
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

oktatas/web/nodejs/rest_api/supertest.txt · Utolsó módosítás: 2022/10/10 23:33 szerkesztette: admin