Test hapi plugins with chaining method calls and assertions.
Using the end method you can write your own assertions in anyway you want.
//chai assertions
var hapiTest = require('hapi-test'),
plugin = require('your-plugin'),
assert = require('chai').assert;
hapiTest({ plugins: [ plugin ] })
.get('/persons')
.end(function (result) {
assert(result.statusCode === 200);
});
If you want to test status code you can simply assert the statusCode number
hapiTest({ plugins: [ plugin ] })
.get('/persons')
.assert(200)
To test a header value you can do an assert with header name as first parameter and header value as second. Works with strings.
//string
hapiTest({plugins: [ plugin ] })
.get('/person')
.assert('connection', 'keep-alive');
If you are using mocha it can handle promises:
it('should 200 on persons', function() {
return hapiTest({ plugins: [ plugin ] })
.get('/person')
.assert(200)
});
If you have multiple tests on the same server / plugins you can create an instance of the server and use this in the constructor. This will speed up the tests as it does not need to create a new server and initialize the plugins for each test.
// example using mocha
var hapiTest = require('hapi-test'),
Hapi = require('@hapi/hapi'),
plugin = require('your-plugin'),
assert = require('chai').assert;
var server;
before(function () {
server = new Hapi.Server({
port: 8888
});
return server.register({
name: 'plugin',
version: '0.0.1',
plugin: plugin.register
});
});
it('can now be used', function () {
return hapiTest({ server })
.get('/person')
.assert(200);
});