【问题标题】:hapijs-lab: Test a route with a valid sessionhapijs-lab:使用有效会话测试路由
【发布时间】:2016-09-18 23:45:19
【问题描述】:

在我的 hapijs 应用程序中,我很少有需要 session 的路线,使用 hapi-auth-cookie 插件进行身份验证策略。我想为这些路线添加一些测试(通过 Lab )。

我找不到任何关于如何为这种情况设置测试的文档(可能是通过 before ?)。任何帮助表示赞赏。提前致谢。

【问题讨论】:

标签: node.js hapijs lab


【解决方案1】:

如果您只需要经过身份验证的用户,只需将用户分配给测试中的credentials 属性即可:

var user = { ... };

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

这是一个演示它的示例:

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

大部分示例取自Authentication Tutorial。

【讨论】:

  • 将credentials 添加到server.inject 选项有效!
  • 现在是 auth: { credentials: users.john } 而不是 credentials
【解决方案2】:

为了在测试期间需要会话,我创建了hapi-session-inject。用法如下

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

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

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

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多