【问题标题】:What is the best approach to test a HapiJS plugin, with Lab?使用 Lab 测试 HapiJS 插件的最佳方法是什么?
【发布时间】:2017-05-31 00:51:36
【问题描述】:

测试 HapiJS 插件的最佳方法是什么,例如添加路由和处理程序的插件。

由于我必须创建一个 Hapi.Server 实例来运行插件,我是否应该为所有插件从应用程序的根目录定义所有测试?

我应该设法在插件的本地测试中获得 Hapi.Server 的实例吗?

如果我选择第二个选项,我的服务器将注册所有插件,包括那些要测试的插件不依赖的插件。

解决这个问题的最佳方法是什么?

提前致谢。

【问题讨论】:

    标签: testing hapijs lab


    【解决方案1】:

    如果您使用Glue(我强烈推荐它),您可以为要执行的每个测试(或测试组)创建一个清单变量。清单只需要包含该测试正确执行所需的插件。

    并公开某种init 函数来实际启动您的服务器。小例子:

    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函数:

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

    【讨论】:

    • 谢谢。我会用的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2020-12-25
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    相关资源
    最近更新 更多