Skip to content
Advertisement

How to test code with Jest that uses readonly fields on mocks of libraries (such as ws socket.readyState)?

I want to unit test this JS code with Jest. It’s using the ws websocket library:

Socket.js

JavaScript

I want to check the error is thrown. For that to happen, I create a mock for the socket and then need to set the readyState of the socket object to CLOSED. The issue is that this is impossible because it’s a readonly field.

Test:

JavaScript

Question: How to test any code that uses readonly fields on mocks of libraries such as socket.readyState?

Edit: Added the mvce on request above.

Advertisement

Answer

The better test strategy is to create a test WebSocket server and connect it. This is also the official team doing, see some test cases. Mocking ws and testing the implementation details is not recommended.

Below testing code using TypeScript:

socket.ts:

JavaScript

socket.test.ts:

JavaScript

Test result:

JavaScript

package versions:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement