当使用 webpack-hot-middleware 配置环境时,Jest 测试失败

4

我正在运行一个非常基础的Jest测试,以测试我的其中一个路由是否返回200。

import request from 'supertest';
import app from './../app';

describe('GET /', () => {
  it('should render properly', async () => {
    await request(app).get('/api/testing').expect(200);
  });
});

这段代码之前都运行良好,但是我配置了webpack-hot-middleware后,在第2行引入app的代码似乎出现了问题。
TypeError: setInterval(...).unref is not a function

  at createEventStream (node_modules/webpack-hot-middleware/middleware.js:50:17)
  at webpackHotMiddleware (node_modules/webpack-hot-middleware/middleware.js:12:21)
  at Object.<anonymous> (server/app.js:62:73)
  at Object.<anonymous> (server/test/routes.test.js:2:38)

如果我从app.js中移除以下代码,测试就可以正常运行。
  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));
  app.get('*', (req, res) => {
    res.write(middleware.fileSystem.readFileSync(path.join(__dirname, '../dist/index.html')));
    res.end();
  });

有人为webpack-hot-middleware配置过Jest吗?我有点迷失,因为我感觉尝试了一切。

2个回答

8

您必须在 Jest 配置选项中设置 testEnvironmentnodeunref() 仅在 Node.js 中存在。


1
将 "jest": { "testEnvironment": "node" } 添加到 package.json 的根级别。 - jws
谢谢 @jws!对我来说,我必须在我的 jest.config.ts 文件中添加 testEnvironment: 'node' - George Dimitriadis

1
通过在文件顶部添加 @jest-environment docblock,您可以指定另一个环境用于该文件中的所有测试,请参考 jest 文档
/**
 * @jest-environment jsdom
 */

import request from 'supertest';
import app from './../app';

describe('GET /', () => {
  it('should render properly', async () => {
    await request(app).get('/api/testing').expect(200);
  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接