Jest referenceError'未定义'

时间:2017-08-15 00:11:46

标签: javascript reactjs jest

我从不直接调用WebSocket,它是Asteroid的依赖。为什么Jest无法加载它? 此外,这应该是一个默认的create-react-app测试,以检查应用程序“呈现而不会崩溃”。但即使开玩笑测试表明它应该崩溃,应用程序也可以正常加载。

我的提交: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 个答案:

答案 0 :(得分:2)

在我发现你可以指定你想在构造函数中使用的websocket之前,我已经被Asteroid窃听了一段时间,如下所示:

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 :(得分:1)

WebSocket类在nodejs中不存在全局,但在浏览器中却存在。您应该在测试时全局模拟或定义此类。我从来没有遇到过这个问题,但我认为你可以试试这个:

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

//your tests...