1import { empty, Source } from 'wonka';
2import { vi, expect, it, beforeEach, describe } from 'vitest';
3
4import { Exchange } from '../types';
5import { composeExchanges } from './compose';
6import { noop } from '../utils';
7
8const mockClient = {} as any;
9
10const forward = vi.fn();
11const noopExchange: Exchange =
12 ({ forward }) =>
13 ops$ =>
14 forward(ops$);
15
16beforeEach(() => {
17 vi.spyOn(Date, 'now').mockReturnValue(1234);
18});
19
20it('composes exchanges correctly', () => {
21 let counter = 0;
22
23 const firstExchange: Exchange = ({ client, forward }) => {
24 expect(client).toBe(mockClient);
25 expect(counter++).toBe(1);
26
27 return ops$ => {
28 expect(counter++).toBe(2);
29 return forward(ops$);
30 };
31 };
32
33 const secondExchange: Exchange = ({ client, forward }) => {
34 expect(client).toBe(mockClient);
35 expect(counter++).toBe(0);
36
37 return ops$ => {
38 expect(counter++).toBe(3);
39 return forward(ops$);
40 };
41 };
42
43 const exchange = composeExchanges([firstExchange, secondExchange]);
44 const outerFw = vi.fn(() => noopExchange) as any;
45
46 exchange({ client: mockClient, forward: outerFw, dispatchDebug: noop })(
47 empty as Source<any>
48 );
49 expect(outerFw).toHaveBeenCalled();
50 expect(counter).toBe(4);
51});
52
53describe('on dispatchDebug', () => {
54 it('dispatches debug event with exchange source name', () => {
55 const dispatchDebug = vi.fn();
56 const debugArgs = {
57 type: 'test',
58 message: 'Hello',
59 } as any;
60
61 const testExchange: Exchange = ({ dispatchDebug }) => {
62 dispatchDebug(debugArgs);
63 return () => empty as Source<any>;
64 };
65
66 composeExchanges([testExchange])({
67 client: mockClient,
68 forward,
69 dispatchDebug,
70 });
71
72 expect(dispatchDebug).toBeCalledTimes(1);
73 expect(dispatchDebug).toBeCalledWith({
74 ...debugArgs,
75 timestamp: Date.now(),
76 source: 'testExchange',
77 });
78 });
79});