Jest参考错误:“未定义”

4
我从未直接调用WebSocket;它是Asteroid的依赖项。为什么Jest无法加载它?
此外,这应该是一个默认的create-react-app测试,用于检查App“无崩溃地渲染”。但是即使Jest测试说应该崩溃,应用程序也可以正常加载。
我的提交:https://github.com/Falieson/typescript-react-asteroid-meteor/commit/ab640bee540f1f2f5da2f0fe7b4be58f75b83d28#commitcomment-23644562
node scripts/test.js --env=jsdom --silent

输出:

 FAIL  src/routes/App.test.tsx
  ● Test suite failed to run

    ReferenceError: WebSocket is not defined

      at Asteroid.init (node_modules/asteroid/lib/base-mixins/ddp.js:46:67)
      at node_modules/asteroid/lib/asteroid.js:72:33
      at Array.forEach (native)
      at new Asteroid (node_modules/asteroid/lib/asteroid.js:70:16)
      at Object.<anonymous> (src/config/asteroid.ts:6:16)
      at Object.<anonymous> (src/routes/Login.tsx:14:18)
      at Object.<anonymous> (src/routes/App.tsx:19:15)
      at Object.<anonymous> (src/routes/App.test.tsx:5:13)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.915s
2个回答

2

在我弄清楚之前,Asteroid困扰了我一段时间。其实你可以在构造函数中指定想要使用的WebSocket,像这样:

const asteroid = require('asteroid');
const WebSocket = require('ws');

const Connection = asteroid.createClass()

const portal = new Connection({
    endpoint: 'ws://localhost:3000/websocket',
    SocketConstructor: WebSocket // <-------------- HERE
})

1

WebSocket 类在 Node.js 中不存在全局,但在浏览器中存在。在测试时,您应该模拟或全局定义此类。我从未遇到过这个特定的问题,但我认为您可以尝试以下方法:

// In App.test.tsx
const WebSocket = require('ws')
global.WebSocket= WebSocket

// Your tests...

谢谢,但那并没有解决问题。 - Falieson

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