2

In my hapijs app I have few routes which require a session, uses hapi-auth-cookie 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 before ?) for this scenario. Any help is appreciated. Thanks in advance.

Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
Sandeep Chayapathi
  • 1,490
  • 2
  • 13
  • 31
  • 1
    You can follow the @Gergo Erdosi example but this https://medium.com/the-spumko-suite/testing-hapi-services-with-lab-96ac463c490a worth a look as well. – Whisher Aug 12 '15 at 14:10
  • 1
    Also this can help http://codereview.stackexchange.com/questions/97975/hapi-lab-e2e-test-workflow – Whisher Aug 12 '15 at 15:49

2 Answers2

4

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) {
    console.log(res.result);
});

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);
    }

    Bcrypt.compare(password, user.password, function (err, isValid) {
        callback(err, isValid, { id: user.id, name: user.name });
    });
};

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

    server.route({
        method: 'GET',
        path: '/',
        config: {
            auth: 'session',
            handler: function (request, reply) {
                reply('hello, ' + request.auth.credentials.name);
            }
        }
    });

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

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

Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
1

For my need for session during testing, I created hapi-session-inject. Usage is as follows

const server = new Hapi.Server();
const session = new Session(server);

// Callback interface
session.inject('/', (res) => {
    ...
});

// Promise interface
return session.inject('/').then((res) => {
    ...
});

Hope it helps.

vinkaga
  • 83
  • 1
  • 6