Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
1// @vitest-environment jsdom
2
3import { pipe, map, makeSubject, publish, tap } from 'wonka';
4import { vi, expect, it, beforeEach } from 'vitest';
5
6import {
7 gql,
8 createClient,
9 Operation,
10 OperationResult,
11 ExchangeIO,
12} from '@urql/core';
13
14import { queryResponse } from '../../../packages/core/src/test-utils';
15import { refocusExchange } from './refocusExchange';
16
17const dispatchDebug = vi.fn();
18
19const queryOne = gql`
20 {
21 author {
22 id
23 name
24 }
25 }
26`;
27
28const queryOneData = {
29 __typename: 'Query',
30 author: {
31 __typename: 'Author',
32 id: '123',
33 name: 'Author',
34 },
35};
36
37let client, op, ops$, next;
38beforeEach(() => {
39 client = createClient({
40 url: 'http://0.0.0.0',
41 exchanges: [],
42 });
43 op = client.createRequestOperation('query', {
44 key: 1,
45 query: queryOne,
46 });
47
48 ({ source: ops$, next } = makeSubject<Operation>());
49});
50
51it(`attaches a listener and redispatches queries on call`, () => {
52 const response = vi.fn((forwardOp: Operation): OperationResult => {
53 return {
54 ...queryResponse,
55 operation: forwardOp,
56 data: queryOneData,
57 };
58 });
59
60 let listener;
61 const spy = vi
62 .spyOn(window, 'addEventListener')
63 .mockImplementation((_keyword, fn) => {
64 listener = fn;
65 });
66 const reexecuteSpy = vi
67 .spyOn(client, 'reexecuteOperation')
68 .mockImplementation(() => ({}));
69
70 const result = vi.fn();
71 const forward: ExchangeIO = ops$ => {
72 return pipe(ops$, map(response));
73 };
74
75 pipe(
76 refocusExchange()({
77 forward,
78 client,
79 dispatchDebug,
80 })(ops$),
81 tap(result),
82 publish
83 );
84
85 expect(spy).toBeCalledTimes(1);
86 expect(spy).toBeCalledWith('visibilitychange', expect.anything());
87
88 next(op);
89
90 listener();
91 expect(reexecuteSpy).toBeCalledTimes(1);
92 expect(reexecuteSpy).toBeCalledWith({
93 context: expect.anything(),
94 key: 1,
95 query: queryOne,
96 kind: 'query',
97 });
98});