testinghapi.jshapi.js-lab

What is the best approach to test a HapiJS plugin, with Lab?


What is the best way to test a HapiJS plugin, for example one plugin that add routes and handlers.

Since I have to create an instance of Hapi.Server to run the plugins, should I define all the tests from the app's root, for all the plugins ?

or

should I manage to get THE instance of Hapi.Server in my plugin's local tests ?

If I go for the second option, my server will have registered all the plugins, including those that the plugin to be tested doesn't depends on.

What is the best way to approach this ?


Solution

  • If you're using Glue (and I highly recommend it), you can create a manifest variable for each test (or group of tests) you want to execute. The manifest only needs to include plugins required for that test to execute properly.

    And expose some sort of init function to actually start your server. Small example:

    import Lab = require("lab");
    import Code = require('code');
    import Path = require('path');
    import Server = require('../path/to/init/server');
    export const lab = Lab.script();
    const it = lab.it;
    const describe = lab.describe;
    
    const config = {...};
    
    const internals = {
        manifest: {
            connections: [
                {
                    host: 'localhost',
                    port: 0
                }
            ],
            registrations: [
                {
                    plugin: {
                        register: '../http_routes',
                        options: config
                    }
                },
                {
                    plugin: {
                        register: '../business_plugin',
                        options: config
                    }
                }
            ]
        },
        composeOptions: {
            relativeTo: 'some_path'
        }
    };
    
    describe('business plugin', function () {
    
        it('should do some business', function (done) {
    
            Server.init(internals.manifest, internals.composeOptions, function (err, server) {
                // run your tests here
            });
        });
    
    });
    

    init function:

    export const init = function (manifest: any, composeOptions: any, next: (err?: any, server?: Hapi.Server) => void) {
        Glue.compose(manifest, composeOptions, function (err: any, server: Hapi.Server) {
    
            if (err) {
                return next(err);
            }
    
            server.start(function (err: any) {
    
                return next(err, server);
            });
        });
    };