Skip to content

Commit

Permalink
Fix code example
Browse files Browse the repository at this point in the history
Changes:
- Fixes trying to emit a connection when the WebSocket is not yet connected.
- Updated AVA test, resolving thoov#388
  • Loading branch information
Borewit committed Feb 2, 2025
1 parent 47eab99 commit 5eff5f5
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,21 @@ class ChatApp {
sendMessage(message) {
this.connection.send(message);
}

static connect(url) {
const chatApp = new ChatApp(url);
return new Promise((resolve, reject) => {
chatApp.connection.addEventListener('open', () => {
resolve(chatApp);
});
chatApp.connection.addEventListener('error', err => {
reject(err);
});
});
}
}

test.cb('that chat app can be mocked', t => {
test('that chat app can be mocked', async t => {
const fakeURL = 'ws://localhost:8080';
const mockServer = new Server(fakeURL);

Expand All @@ -64,15 +76,14 @@ test.cb('that chat app can be mocked', t => {
});
});

const app = new ChatApp(fakeURL);
const app = await ChatApp.connect(fakeURL);
app.sendMessage('test message from app'); // NOTE: this line creates a micro task

// NOTE: this timeout is for creating another micro task that will happen after the above one
setTimeout(() => {
t.is(app.messages.length, 1);
t.is(app.messages[0], 'test message from mock server', 'we have stubbed our websocket backend');
mockServer.stop(t.done);
}, 100);
await new Promise(resolve => setTimeout(resolve, 100));

t.is(app.messages.length, 1);
t.is(app.messages[0], 'test message from mock server', 'we have stubbed our websocket backend');
mockServer.stop(t.done);
});
```

Expand Down

0 comments on commit 5eff5f5

Please sign in to comment.