Sandeep Chayapathi Sandeep Chayapathi - 1 year ago 158
Node.js Question

hapijs-lab: Test a route with a valid session

In my hapijs app I have few routes which require a

, uses
plugin for auth strategy. I want to add few tests (via Lab ) for these routes.

I couldn't find any documentation on how I can setup a test (maybe via
?) for this scenario. Any help is appreciated. Thanks in advance.

Answer Source

If you only need an authenticated user, just assign the user to the credentials property in tests:

var user = { ... };

server.inject({ method: 'GET', url: '/', credentials: user }, function (res) {

Here is an example that demonstrates it:

var Bcrypt = require('bcrypt');
var Hapi = require('hapi');
var HapiAuthCookie = require('hapi-auth-cookie');

var server = new Hapi.Server();
server.connection({ port: 3000 });

var users = {
    john: {
        username: 'john',
        password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm',
        name: 'John Doe',
        id: '2133d32a'

var validate = function (request, username, password, callback) {
    var user = users[username];
    if (!user) {
        return callback(null, false);
    }, user.password, function (err, isValid) {
        callback(err, isValid, { id:, name: });

server.register(HapiAuthCookie, function (err) {
    server.auth.strategy('session', 'cookie', {
        password: 'secret',
        validateFunc: validate

        method: 'GET',
        path: '/',
        config: {
            auth: 'session',
            handler: function (request, reply) {
                reply('hello, ' +;

    server.inject({ method: 'GET', url: '/', credentials: users.john }, function (res) {

Large part of the example was taken from the Authentication Tutorial.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download