Jest referenceError“未定义”
2017-08-15
13403
我从未直接调用 WebSocket;它是 Asteroid 的依赖项。为什么 Jest 无法加载它?
此外,这应该是默认的
create-react-app
测试,用于检查应用程序“渲染时不会崩溃”。但是即使 Jest 测试表明应用程序应该崩溃,它仍可以正常加载。
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个回答
我被 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
})
holmrenser
2017-08-15
WebSocket
类在 Node.js 中不全局存在,但在浏览器中却存在。您应该在测试时全局模拟或定义此类。我从未遇到过这个特殊问题,但我认为您可以尝试以下方法:
// In App.test.tsx
const WebSocket = require('ws')
global.WebSocket= WebSocket
// Your tests...
GProst
2017-08-15