【问题标题】:Jest TestEnvironment - TypeError: Cannot add property next, object is not extensibleJest TestEnvironment - TypeError:无法添加属性,对象不可扩展
【发布时间】:2022-05-04 23:04:32
【问题描述】:

我想使用 Jest 测试节点 API。我正在测试路由和 websocket。测试路线没有问题。我只是使用setupFile 选项启动了服务器。
为了测试 websocket,我想将 io 对象传递给测试。这通过 setupFile 是不可能的,因为测试是在它们自己的上下文中运行的。因此我改为testEnvironment 选项。我的 testEnvironment 文件如下

const NodeEnvironment = require('jest-environment-node');

class CustomEnvironment extends NodeEnvironment {
  constructor(config, context) {
    super(config, context);
    this.setupServer();
  }

  async setup() {
    await super.setup();
    console.log('Setup Test Environment.');
    this.global.io = this.io;
    this.global.baseUrl = 'http://localhost:' + this.port;
  }

  async teardown() {
    await super.teardown();
    console.log('Teardown Test Environment.');
  }

  getVmContext() {
    return super.getVmContext();
  }

  setupServer() {
    // Code for starting the server and attaching the io object
    this.port = portConfig.http;
    this.io = io;
  }
}

module.exports = CustomEnvironment;

这可行并且 io 对象被传递给测试。我有多个针对 API 不同部分的测试文件。使用setupFile 运行那些没有问题,但现在 Jest 只能运行一个文件。以下所有测试套件均失败并显示以下消息

● Test suite failed to run

    TypeError: Cannot add property next, object is not extensible

      at Function.handle (node_modules/express/lib/router/index.js:160:12)
      at Function.handle (node_modules/express/lib/application.js:174:10)
      at new app (node_modules/express/lib/express.js:39:9)

我找不到有关该错误的任何文档。我尝试禁用一些测试文件,但它总是在第一个之后失败,无论它是哪个。

如果相关,测试文件的结构如下:

const axios = require('axios');

describe('Test MODULE routes', () => {
  const baseUrl = global.baseUrl;
  const io = global.io;
  const models = require('../../../models'); // sequelize models which are used in tests

  describe('HTTP METHOD + ROUTE', () => {
    test('ROUTE DESCRIPTION', async () => {
      const response = await axios({
        method: 'get',
        url: baseUrl + 'ROUTE'
      });

      expect(response.status).toBe(200);
    });
  });

  // different routes
});

【问题讨论】:

    标签: javascript node.js express jestjs


    【解决方案1】:

    我修复了错误。它与开玩笑无关,但与服务器设置中的 module.exports 调用有关,该调用用快速服务器覆盖了 CustomEnvironment 的导出。

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2020-09-03
      • 2020-06-07
      • 1970-01-01
      • 2019-08-29
      • 2020-06-23
      相关资源
      最近更新 更多