为什么我在使用实验室库的 HapiJS 测试中得到未定义的值>

Why I get an undefined value in this HapiJS test using Lab library>

我正在按照 HapiJS 教程创建服务器并使用单元测试。

'use strict'

const Hapi = require('@hapi/hapi')

module.exports = async (host, port, router) => {
  if (!host) {
    const error = new Error('Host missed')
    console.error(error)
    process.exit(1)
  }
  if (!port) {
    const error = new Error('Port missed')
    console.error(error)
    process.exit(1)
  }

  const server = Hapi.server({
    host,
    port,
    compression: {
      minBytes: 2048
    },
    router: {
      isCaseSensitive: false
    },
    state: {
      isSameSite: false, // change later
    }
  })

  server.route(router)

  await server.start()
  console.log('Server running on %s', server.info.uri)
}

这是我的 server.js 文件。我创建了一个将在 index.js 调用的导出函数。这个函数有三个参数。第一个参数是主机,第二个是端口,第三个是带路由的非结构化对象。显然它工作正常。

这是我的路线示例:

const users = [
  {
    method: 'GET',
    path: '/users',
    handler: (req, h) => {
      return 'Hello World'
    }
  },
  {
    method: 'POST',
    path: '/users',
    handler: (req, h) => {
      return 'Hello World'
    }
  },
  {
    method: 'PUT',
    path: '/users/:id',
    handler: (req, h) => {
      return 'Hello World'
    }
  },
  {
    method: 'DELETE',
    path: '/users/:id',
    handler: (req, h) => {
      return 'Hello World'
    }
  }
]

module.exports = users

这是处理程序:

const users = require('./components/users/network')
const articles = require('./components/articles/network') // This one is very similar to users

module.exports = [...users, ...articles]

这是我创建的测试,用于验证服务器初始化是否正常工作:

'use strict';

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

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

    beforeEach(async () => {
        server = await init('localhost', 8080, routes);
    });

    console.log(server)

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

但是我得到以下输出错误:

lab

undefined Server running on http://localhost:8080

x

Failed tests:

  1. GET /users responds with 200:

    Cannot read property 'inject' of undefined

    at C:\Users\diesa\Dropbox\My PC (LAPTOP-21VAS36L)\Desktop\kemus-blog\test\server\init.test.js:19:34 at Immediate. (C:\Users\diesa\Dropbox\My PC (LAPTOP-21VAS36L)\Desktop\kemus-blog\node_modules@hapi\lab\lib\runner.js:661:35) at processImmediate (internal/timers.js:461:21)

1 of 1 tests failed Test duration: 59 ms Leaks: No issues

npm ERR! Test failed. See above for more details.

为什么未定义变量服务器?我以为是节点的异步问题,结果不是。

您的 init 函数没有 returning 一个值。我想你想把它改成 return 服务器。

await server.start();
console.log('Server running on %s', server.info.uri);
return server;