hapi lab AssertionError [ERR_ASSERTION]:插件屑已经注册 [英] hapi lab AssertionError [ERR_ASSERTION]: Plugin crumb already registered

查看:157
本文介绍了hapi lab AssertionError [ERR_ASSERTION]:插件屑已经注册的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定为什么会收到此邮件.我正在尝试使用@hapi/crumb创建一个简单的测试.我只在我的server.js中注册一次.

i'm not sure why i am receiving this. I am trying to create a simple test while using @hapi/crumb. i am only registering it once in my server.js.

const Path = require("path");
const hapi = require("hapi");
const inert = require("inert");
const vision = require("vision");
const Ejs = require("ejs");
const Crumb = require("@hapi/crumb");
const Blankie = require("blankie");
const Scooter = require("@hapi/scooter");
const routes = require("./routes");

// Configure the server
const server = hapi.Server({
  host: "0.0.0.0",
  port: process.env.PORT || 3000,
  routes: {
    files: {
      relativeTo: Path.join(__dirname, "..", "public")
    },
    state: {
      parse: true,
      failAction: "ignore"
    },
    security: {
      xframe: true,
      noOpen: false
    },
    cors: {
      origin: ["banglarelief.org"],
      headers: ["Authorization"], // an array of strings - 'Access-Control-Allow-Headers'
      exposedHeaders: ["Accept"], // an array of exposed headers - 'Access-Control-Expose-Headers',
      additionalExposedHeaders: ["Accept"], // an array of additional exposed headers
      maxAge: 60,
      credentials: true // boolean - 'Access-Control-Allow-Credentials'
    }
  }
});

const plugins = async () => {
  const pluginsToRegister = [
    inert,
    vision,
    require("hapi-mobile-views"),
    { plugin: Crumb, options: { cookieOptions: { isSecure: false } } },
    Scooter,
    {
      plugin: Blankie,
      options: {} // specify options here
    }
  ];
  await server.register(pluginsToRegister);
};

const init = async () => {
  await plugins();
  server.state("player", {
    ttl: null,
    clearInvalid: true,
    isSecure: false
  });
  server.views({
    engines: { ejs: Ejs },
    path: `${__dirname}/views`,
    layout: "layout"
  });
  await server.route(routes);
  return server;
};


const start = async () => {
  try {
    await init();
    await server.start();
  } catch (err) {
    console.log(err);
    process.exit(1);
  }
};

module.exports = { init, start };

我的测试文件非常基础,我尝试移动应该调用开始的位置,但它始终抛出相同的错误.

My test file is very basic and i have tried to move around where the start should be called but it keep throwing same error.

'use strict';

const Lab = require('@hapi/lab');
const { expect } = require('@hapi/code');
const { afterEach, beforeEach, describe, it } = exports.lab = Lab.script();
const { init, start } = require('../src/server');

let server = start();

describe('GET /', () => {
    //let server;
    //server = start();

    beforeEach(async () => {
        //server = start();
    });

    afterEach(async () => {
        //await server.stop();
    });

    it('responds with 200', async () => {
        const res = await server.inject({
            method: 'get',
            url: '/'
        });
        expect(res.statusCode).to.equal(200);
    });
});

我一直在关注 https://hapijs.com/tutorials/testing?lang=zh_CN

推荐答案

如果将plugins函数分为两部分,则该解决方案似乎可以正常工作.一部分将初始化@Hapi/*之类的第三方插件.另一个功能将初始化您编写的第一方插件.您只能在start函数中初始化第三方插件.

The solution seems to work if you break up your plugins function into two parts. One part will init 3rd party plugins like @Hapi/*. The other function will init your 1st party plugins that you wrote. You will only init the 3rd party plugins in your start function.

包括{ once: true }至关重要,因为这样可以防止出现错误.它只会初始化一次插件,这将防止您出错.您不能总是在第三方插件上指定{ once: true }.因此,我们必须以不同的方式来处理.由于我们将所有第3方插件都移到了自己的函数(在启动时调用),因此应该可以防止第3方插件引起重新初始化的问题.

It's critical that you include { once: true } because that will prevent your error. It will only initialize the plugin once, which will prevent your error. You cannot always specify { once: true } on 3rd party plugins. Thus, we have to handle that a different way. Since we moved all the 3rd party plugins to their own function, which is invoked on start, that should prevent 3rd party plugins from causing an issue of being reinitialized.

const hapiPlugins = async () => {
  const pluginsToRegister = [
    inert,
    vision,
    require("hapi-mobile-views"),
    { plugin: Crumb, options: { cookieOptions: { isSecure: false } } },
    Scooter,
    {
      plugin: Blankie,
      options: {} // specify options here
    }
  ];
};

const myPlugins = async () => {
  await server.register([
    allOfMyPlugins...
  ],
  {
    once: true  //critical so that you don't re-init your plugins
  });
};

const init = async () => {
  server.state("player", {
    ttl: null,
    clearInvalid: true,
    isSecure: false
  });
  server.views({
    engines: { ejs: Ejs },
    path: `${__dirname}/views`,
    layout: "layout"
  });
  await server.route(routes);
  return server;
};


const start = async () => {
  try {
    await hapiPlugins();
    await init();
    await server.start();
  } catch (err) {
    console.log(err);
    process.exit(1);
  }
};

然后,您应该可以在测试的before函数中调用init.使用该服务器对象进行注入.

Then, you should be able to call init in your test's before function. Use that server object to inject.

这篇关于hapi lab AssertionError [ERR_ASSERTION]:插件屑已经注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆