forked from janek26/trpc-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
relay.test.ts
65 lines (54 loc) · 1.86 KB
/
relay.test.ts
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
56
57
58
59
60
61
62
63
64
65
import { getMockChrome, getMockWindow } from './__setup';
import { relay } from '../src/relay';
import { isTRPCMessage } from '../src/shared/trpcMessage';
import type { TRPCChromeMessage } from '../src/types';
const mockMessage: TRPCChromeMessage = {
trpc: {
id: '1',
result: {
type: 'data',
data: {
payload: 'hello',
},
},
},
};
describe('relay', () => {
test('validate test data', () => {
expect(isTRPCMessage(mockMessage)).toBe(true);
});
test('relays messages between window to port', () => {
const chrome = getMockChrome();
const port = chrome.runtime.connect();
const handlerPort = chrome.__handlerPort; // only in mock chrome
const window = getMockWindow();
const cleanup = relay(window, port);
expect(port.onMessage.addListener).toHaveBeenCalledTimes(1);
expect(port.onDisconnect.addListener).toHaveBeenCalledTimes(0);
expect(port.onDisconnect.removeListener).toHaveBeenCalledTimes(0);
expect(port.onMessage.removeListener).toHaveBeenCalledTimes(0);
expect(port.postMessage).toHaveBeenCalledTimes(0);
expect(window.addEventListener).toHaveBeenCalledTimes(1);
expect(window.removeEventListener).toHaveBeenCalledTimes(0);
expect(window.postMessage).toHaveBeenCalledTimes(0);
window.postMessage(mockMessage);
expect(port.postMessage).toHaveBeenCalledTimes(1);
expect(port.postMessage).toHaveBeenCalledWith({
...mockMessage,
relayed: true,
});
handlerPort.postMessage(mockMessage);
expect(window.postMessage).toHaveBeenCalledTimes(2);
expect(window.postMessage).toHaveBeenCalledWith(
{
...mockMessage,
relayed: true,
},
{ targetOrigin: undefined },
);
cleanup();
window.postMessage(mockMessage);
handlerPort.postMessage(mockMessage);
expect(port.postMessage).toHaveBeenCalledTimes(1);
});
});