1

react native built-in global objects like WebSocket does not exist in runnig jest's test

i'm testin my RN app using jest . trying to access RN built-in global WebSocket Object in test files give me undefined. whereas access the object in running app has no problem

app.test.js

console.log(typeof WebSocekt);// return undefined

app.js

console.log(typeof WebSocekt);// return function

expected the WebSocket in jest runner to be function but got undefined as result.

skyboyer
  • 22,209
  • 7
  • 57
  • 64

1 Answers1

1

Actually, the WebSocket class doesn't exist globally inside nodejs, but in browsers it does. You can specify the WebSocket you want to use in the constructor like this:

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

const Connection = asteroid.createClass()

const portal = new Connection({
  endpoint: 'ws://localhost:3000/websocket',
  SocketConstructor: WebSocket // <-------------- HERE
}) 
Yevhen Laichenkov
  • 7,746
  • 2
  • 27
  • 33