jest-websocket-mock icon indicating copy to clipboard operation
jest-websocket-mock copied to clipboard

SyntaxError: Unexpected token 'export'

Open inuitviking opened this issue 1 year ago • 0 comments

Hi!

I'm trying to write some tests against a server that already exists (currently locally).

NodeJS: v21.7.3 NPM: 10.8.0

I tried following this guide in the README: https://github.com/romgain/jest-websocket-mock?tab=readme-ov-file#using-jest-websocket-mock-to-interact-with-a-non-global-websocket-object

It fails with this error:

    Details:

    /var/projekter/pace-proxy-client/jest/__mocks__/ws.js:3
    export { WebSocket as default } from "mock-socket";
    ^^^^^^

    SyntaxError: Unexpected token 'export'

    > 1 | const WebSocket = require('ws');
        |                                ^

Changing it to const WebSocket = require('mock-socket'); results in this error:

    TypeError: WebSocket is not a constructor

      17 |
      18 | test("the server keeps track of received messages, and yields them as they come in", async () => {
    > 19 |      const client = new WebSocket("ws://localhost:3000/pace");

I'm not sure what I'm doing wrong, but I'm also not very well versed in NodeJS (or JS in general).

Full test file is here:

const WebSocket = require('ws');
const WS = require('jest-websocket-mock');

test("test response from server", async () => {
	const client = new WebSocket("ws://localhost:3000/endpoint");
	client.on('error', console.error);

	client.on('open', async function open() {
		client.send('hello');
		await expect(client).toReceiveMessage("hello");
	});

	expect(client).toHaveReceivedMessages(["hello"]);
});

What am I doing wrong? Don't think I have found anything in other issues or any documentation that is about this issue (either that, or I didn't understand. :sweat_smile: )

inuitviking avatar May 23 '24 10:05 inuitviking