【问题标题】:Jest referenceError 'is not defined'开玩笑referenceError'未定义'
【发布时间】:2017-08-15 00:11:46
【问题描述】:

我从不直接调用 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

感谢您的帮助

【问题讨论】:

    标签: javascript reactjs jestjs


    【解决方案1】:

    在我发现你可以像这样在构造函数中指定要使用的 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
    })
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 谢谢,但这并没有解决问题
      猜你喜欢
      • 1970-01-01
      • 2022-07-12
      • 2021-09-17
      • 2021-09-06
      • 2020-05-29
      • 2022-10-16
      • 2021-07-17
      • 2020-03-17
      • 2017-11-01
      相关资源
      最近更新 更多