All files / specs socket.mock.ts

100% Statements 25/25
100% Branches 4/4
100% Functions 6/6
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 561x   1x 16x 16x 16x   16x   16x 16x 16x 16x   16x 24x 24x 24x 24x                         16x     16x 16x 16x 16x           6x 6x         2x 2x 2x        
import { jest } from '@jest/globals';
 
export class MockWebSocket {
    public onmessage: ((event: MessageEvent) => void) | null = null;
    public onopen: (() => void) | null = null;
    public onclose: (() => void) | null = null;
 
    public readyState = 0; // CONNECTING
 
    public CONNECTING = 0;
    public OPEN = 1;
    public CLOSING = 2;
    public CLOSED = 3;
 
    send = jest.fn((data: string) => {
        const parsedData = JSON.parse(data);    
        setTimeout(() => {
            if (this.onmessage) {
                this.onmessage({
                    data: JSON.stringify({
                        SERVICE_NAME: 'mock-test',
                        SERVICE_VERS: '1.0.0',
                        MESSAGE_UUID: parsedData.UUIDV4,
                        MESSAGE_EXEC: 'SUCCESS',
                        MESSAGE_DATA: 'mock data response'
                    })
                } as MessageEvent);
            }
        }, 0);
    });
 
    close = jest.fn();
 
    constructor() {
        setTimeout(() => {
            this.readyState = this.OPEN;
            if (this.onopen) {
                this.onopen();
            }
        }, 0);
    }
 
    triggerMessage(data: any) {
        if (this.onmessage) {
            this.onmessage({ data: JSON.stringify(data) } as MessageEvent);
        }
    }
 
    triggerClose() {
        this.readyState = this.CLOSED;
        if (this.onclose) {
            this.onclose();
        }
    }
}