forwardemail / forwardemail/supertest

How do I use this with socket.io?

Open
#572 1 comment 12 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
14.4k
Forks
782
PR merge metrics
No merged PRs in 30d

Description

Hey!

I have an `express.js` server + `socket.io` server. I wrote some tests using `supertest` and `jest` and it was great! However right now I have to write tests for `socket.io.` I ran almost immediately into some issues. Basically I have the following code

```ts
const server = http.createServer(app);

const io = createSocketIoServer(server);

const initServer = async () => {
// ...
// Irrelevant code
// ...

return server;
};

const startServer = async () => {
(await initServer()).listen(PORT, () => {
console.log(`🥩 Luncher-box backend running on ${BACKEND_URL} in ${ENV}`);
});
};

if (ENV !== 'test') {
startServer();
}
```

And as you can see, I only start the server when **NOT** in `test`-ing. That is supposed to be the case for when I'm doing normal `express` requests using `supertest` (using `request` and passing my server -> `request(server)
.post('/foo')`).

However I need to start the server in order to init my `socket.io` connection.

What's the best way to handle this? Is there some way to connect to the underlying server, provided by `supertest` if there is any running?

Edit: If I start the server, my test doesn't pass.

```ts
import { Server } from 'http';
import io from 'socket.io-client';
import { Connection } from 'typeorm';
import { initServer, startServer } from '../src';
import { io as ioServer, SOCKET_URL } from '../src/config';
import { dbConnection as getDbConnection } from '../src/connections';

let server: Server;
let dbConnection: Connection;
let ioClient: SocketIOClient.Socket;

beforeAll(async () => {
server = await initServer();
await startServer(server);
dbConnection = await getDbConnection();
});

beforeEach(done => {
ioClient = io(SOCKET_URL, {
reconnection: true,
forceNew: true,
transports: ['websocket']
});

ioClient.on('connect', () => {
done();
});
});

afterEach(done => {
if (ioClient.connected) {
ioClient.disconnect();
}

done();
});

describe('Connect to socket.io', () => {
it('connects to the backend via socket.io ', done => {
const message = 'Hello World';
ioClient.emit('socket_connect', message);

ioClient.on('socket_connected', (recievedMessage: string) => {
expect(recievedMessage).toBe(message);
done();
});

ioServer.on('connection', mySocket => {
expect(mySocket).toBeDefined();
});
});
});
```

And if I start my dev server from a seperate terminal, the test passes (???)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.