I'm using Cypress to connect to a websocket server using the browser's websocket API. The it()
block is one test step and a describe()
block is another:
const ws = new WebSocket(wsUrl);
it("Send a message to WSS", (done) => {
ws.onopen = () => {
ws.send(Message);
done();
};
});
it("Close WSS connection", (done) => {
ws.close();
ws.onclose = () => {
done();
};
});`
Everything works when I run the tests individually in Test Runner, but when I run a test suite with multiple tests (each test opening and closing the connection) more often than not the first passes and the 2nd fails upon establishing connection. I'm getting error code 200 with a failed handshake message. Sometimes 2 tests pass and the 3rd fails. Sometimes they all pass.
I tried hard waiting after each test/file with 1 describe block so the session clears but to no avail.
So in the Cypress Test Runner, it appears that all three WebSocket connections are being established at the beginning of the first test because the
const ws = new WebSocket(wsUrl);
statement is executed immediately when the test file is loaded. This is outside of any specific test (it block), so it runs as soon as the script is parsed, not when the tests are actually executed.
So the answer is that the connection to wss has to be in an 'it' block otherwise it will be executed for all tests at once at the beginning of test suite execution.
E.g.:
let ws;
// Pre-conditions & action
it("Connect to & send a message", (done) => {
ws = new WebSocket(wsUrl);
ws.onopen = () => {
ws.send(message);
done();
};
});