Gathering detailed insights and metrics for supertest
Gathering detailed insights and metrics for supertest
Gathering detailed insights and metrics for supertest
Gathering detailed insights and metrics for supertest
🕷 Super-agent driven library for testing node.js HTTP servers using a fluent API. Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
npm install supertest
53.5
Supply Chain
99
Quality
82.9
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
13,833 Stars
476 Commits
759 Forks
115 Watching
1 Branches
92 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-5.2%
1,102,408
Compared to previous day
Last week
2.3%
6,259,709
Compared to previous week
Last month
14.2%
25,518,423
Compared to previous month
Last year
22.9%
240,967,383
Compared to previous year
HTTP assertions made easy via superagent. Maintained for Forward Email and Lad.
The motivation with this module is to provide a high-level abstraction for testing HTTP, while still allowing you to drop down to the lower-level API provided by superagent.
Install SuperTest as an npm module and save it to your package.json file as a development dependency:
1npm install supertest --save-dev
Once installed it can now be referenced by simply calling require('supertest');
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.
SuperTest works with any test framework, here is an example without using any test framework at all:
1const request = require('supertest'); 2const express = require('express'); 3 4const app = express(); 5 6app.get('/user', function(req, res) { 7 res.status(200).json({ name: 'john' }); 8}); 9 10request(app) 11 .get('/user') 12 .expect('Content-Type', /json/) 13 .expect('Content-Length', '15') 14 .expect(200) 15 .end(function(err, res) { 16 if (err) throw err; 17 });
To enable http2 protocol, simply append an options to request
or request.agent
:
1const request = require('supertest'); 2const express = require('express'); 3 4const app = express(); 5 6app.get('/user', function(req, res) { 7 res.status(200).json({ name: 'john' }); 8}); 9 10request(app, { http2: true }) 11 .get('/user') 12 .expect('Content-Type', /json/) 13 .expect('Content-Length', '15') 14 .expect(200) 15 .end(function(err, res) { 16 if (err) throw err; 17 }); 18 19request.agent(app, { http2: true }) 20 .get('/user') 21 .expect('Content-Type', /json/) 22 .expect('Content-Length', '15') 23 .expect(200) 24 .end(function(err, res) { 25 if (err) throw err; 26 });
Here's an example with mocha, note how you can pass done
straight to any of the .expect()
calls:
1describe('GET /user', function() { 2 it('responds with json', function(done) { 3 request(app) 4 .get('/user') 5 .set('Accept', 'application/json') 6 .expect('Content-Type', /json/) 7 .expect(200, done); 8 }); 9});
You can use auth
method to pass HTTP username and password in the same way as in the superagent:
1describe('GET /user', function() { 2 it('responds with json', function(done) { 3 request(app) 4 .get('/user') 5 .auth('username', 'password') 6 .set('Accept', 'application/json') 7 .expect('Content-Type', /json/) 8 .expect(200, done); 9 }); 10});
One thing to note with the above statement is that superagent now sends any HTTP
error (anything other than a 2XX response code) to the callback as the first argument if
you do not add a status code expect (i.e. .expect(302)
).
If you are using the .end()
method .expect()
assertions that fail will
not throw - they will return the assertion as an error to the .end()
callback. In
order to fail the test case, you will need to rethrow or pass err
to done()
, as follows:
1describe('POST /users', function() { 2 it('responds with json', function(done) { 3 request(app) 4 .post('/users') 5 .send({name: 'john'}) 6 .set('Accept', 'application/json') 7 .expect('Content-Type', /json/) 8 .expect(200) 9 .end(function(err, res) { 10 if (err) return done(err); 11 return done(); 12 }); 13 }); 14});
You can also use promises:
1describe('GET /users', function() { 2 it('responds with json', function() { 3 return request(app) 4 .get('/users') 5 .set('Accept', 'application/json') 6 .expect('Content-Type', /json/) 7 .expect(200) 8 .then(response => { 9 expect(response.body.email).toEqual('foo@bar.com'); 10 }) 11 }); 12});
Or async/await syntax:
1describe('GET /users', function() { 2 it('responds with json', async function() { 3 const response = await request(app) 4 .get('/users') 5 .set('Accept', 'application/json') 6 expect(response.headers["Content-Type"]).toMatch(/json/); 7 expect(response.status).toEqual(200); 8 expect(response.body.email).toEqual('foo@bar.com'); 9 }); 10});
Expectations are run in the order of definition. This characteristic can be used to modify the response body or headers before executing an assertion.
1describe('POST /user', function() { 2 it('user.name should be an case-insensitive match for "john"', function(done) { 3 request(app) 4 .post('/user') 5 .send('name=john') // x-www-form-urlencoded upload 6 .set('Accept', 'application/json') 7 .expect(function(res) { 8 res.body.id = 'some fixed id'; 9 res.body.name = res.body.name.toLowerCase(); 10 }) 11 .expect(200, { 12 id: 'some fixed id', 13 name: 'john' 14 }, done); 15 }); 16});
Anything you can do with superagent, you can do with supertest - for example multipart file uploads!
1request(app) 2 .post('/') 3 .field('name', 'my awesome avatar') 4 .field('complex_object', '{"attribute": "value"}', {contentType: 'application/json'}) 5 .attach('avatar', 'test/fixtures/avatar.jpg') 6 ...
Passing the app or url each time is not necessary, if you're testing
the same host you may simply re-assign the request variable with the
initialization app or url, a new Test
is created per request.VERB()
call.
1request = request('http://localhost:5555'); 2 3request.get('/').expect(200, function(err){ 4 console.log(err); 5}); 6 7request.get('/').expect('heya', function(err){ 8 console.log(err); 9});
Here's an example with mocha that shows how to persist a request and its cookies:
1const request = require('supertest'); 2const should = require('should'); 3const express = require('express'); 4const cookieParser = require('cookie-parser'); 5 6describe('request.agent(app)', function() { 7 const app = express(); 8 app.use(cookieParser()); 9 10 app.get('/', function(req, res) { 11 res.cookie('cookie', 'hey'); 12 res.send(); 13 }); 14 15 app.get('/return', function(req, res) { 16 if (req.cookies.cookie) res.send(req.cookies.cookie); 17 else res.send(':(') 18 }); 19 20 const agent = request.agent(app); 21 22 it('should save cookies', function(done) { 23 agent 24 .get('/') 25 .expect('set-cookie', 'cookie=hey; Path=/', done); 26 }); 27 28 it('should send cookies', function(done) { 29 agent 30 .get('/return') 31 .expect('hey', done); 32 }); 33});
There is another example that is introduced by the file agency.js
Here is an example where 2 cookies are set on the request.
1agent(app) 2 .get('/api/content') 3 .set('Cookie', ['nameOne=valueOne;nameTwo=valueTwo']) 4 .send() 5 .expect(200) 6 .end((err, res) => { 7 if (err) { 8 return done(err); 9 } 10 expect(res.text).to.be.equal('hey'); 11 return done(); 12 });
You may use any superagent methods,
including .write()
, .pipe()
etc and perform assertions in the .end()
callback
for lower-level needs.
Assert response status
code.
Assert response status
code and body
.
Assert response body
text with a string, regular expression, or
parsed body object.
Assert header field
value
with a string or regular expression.
Pass a custom assertion function. It'll be given the response object to check. If the check fails, throw an error.
1request(app) 2 .get('/') 3 .expect(hasPreviousAndNextKeys) 4 .end(done); 5 6function hasPreviousAndNextKeys(res) { 7 if (!('next' in res.body)) throw new Error("missing next key"); 8 if (!('prev' in res.body)) throw new Error("missing prev key"); 9}
Perform the request and invoke fn(err, res)
.
Inspired by api-easy minus vows coupling.
MIT
No vulnerabilities found.
No security vulnerabilities found.