Skip to content

Commit

Permalink
fix: add mock websockets client (#321)
Browse files Browse the repository at this point in the history
* fix: add mock websockets client

* fix: add jest cache for speed
  • Loading branch information
spaenleh authored Jun 29, 2023
1 parent 65b2ee2 commit b8734b8
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ yarn-error.log*

# cache
.eslintcache
.jest-cache

# testing and coverage
cypress/screenshots
Expand Down
2 changes: 1 addition & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default {
// bail: 0,

// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/8n/0bjjpkw94_97_lywdtll_d0r0000gn/T/jest_dx",
cacheDirectory: '.jest-cache',

// Automatically clear mock calls and instances between every test
// clearMocks: false,
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export { DATA_KEYS } from './config/keys';
export { API_ROUTES } from './api/routes';

export * from './types';
export { MockWebSocket } from './ws';
1 change: 1 addition & 0 deletions src/ws/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
*/
export * from './hooks';
export { configureWebsocketClient } from './ws-client';
export { default as MockWebSocket } from './mock-ws-client';
59 changes: 59 additions & 0 deletions src/ws/mock-ws-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* Mock WebSocket class for Graasp WS protocol
*/

export default class MockWebSocket {
CLOSED: number;

OPEN: number;

readyState: number;

onopen?: () => void;

onmessage?: (msg: unknown) => void;

constructor() {
this.CLOSED = 0;
this.OPEN = 1;

this.readyState = this.OPEN;

this.send = this.send.bind(this);
this.receive = this.receive.bind(this);
this.addEventListener = this.addEventListener.bind(this);
}

send(msg: string) {
const req = JSON.parse(msg);
// acknowledge request
if (req.action.includes('subscribe')) {
const res = {
data: JSON.stringify({
realm: 'notif',
type: 'response',
status: 'success',
request: req,
}),
};
this.onmessage?.(res);
}
}

receive(msg: object) {
const event = {
data: JSON.stringify(msg),
};
this.onmessage?.(event);
}

addEventListener(
event: 'message' | 'open',
handler: (message?: unknown) => void,
) {
this[`on${event}`] = handler;
if (event === 'open') {
handler();
}
}
}

0 comments on commit b8734b8

Please sign in to comment.