-
Notifications
You must be signed in to change notification settings - Fork 5
/
subscription-storage.spec.ts
88 lines (72 loc) · 2.39 KB
/
subscription-storage.spec.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { Subject } from 'rxjs';
import { QueryClient, QueryCache } from 'react-query';
import {
storeSubscription,
cleanupSubscription,
} from '../subscription-storage';
describe('subscription storage', () => {
let queryCache: QueryCache;
let queryClient: QueryClient;
beforeEach(() => {
queryCache = new QueryCache();
queryClient = new QueryClient({
queryCache,
defaultOptions: {
queries: { retry: false },
},
});
});
afterEach(() => {
queryCache.clear();
});
function subscriptionFactory<T>(observerFn?: (value: T) => void) {
const subject = new Subject<T>();
const subscription = subject.asObservable().subscribe(observerFn);
return {
subscription,
next: (value: T) => subject.next(value),
observerFn,
};
}
test('store and cleanup subscription', () => {
const observerFn = jest.fn();
const { subscription, next } = subscriptionFactory(observerFn);
storeSubscription(queryClient, 'test', subscription);
next('value-1');
expect(observerFn).toHaveBeenCalledTimes(1);
expect(observerFn).toHaveBeenCalledWith('value-1');
observerFn.mockClear();
cleanupSubscription(queryClient, 'test');
next('value-2');
expect(observerFn).not.toHaveBeenCalled();
});
test('only unsubscribes the specified subscription', () => {
const observerAFn = jest.fn();
const { subscription: subscriptionA, next: nextA } =
subscriptionFactory(observerAFn);
const observerBFn = jest.fn();
const { subscription: subscriptionB, next: nextB } =
subscriptionFactory(observerBFn);
storeSubscription(queryClient, 'testA', subscriptionA);
storeSubscription(queryClient, 'testB', subscriptionB);
nextA('A1');
expect(observerAFn).toHaveBeenCalledTimes(1);
expect(observerAFn).toHaveBeenCalledWith('A1');
observerAFn.mockClear();
nextB('B1');
expect(observerBFn).toHaveBeenCalledTimes(1);
expect(observerBFn).toHaveBeenCalledWith('B1');
observerBFn.mockClear();
cleanupSubscription(queryClient, 'testA');
nextA('A2');
expect(observerAFn).not.toHaveBeenCalled();
nextB('B2');
expect(observerBFn).toHaveBeenCalledTimes(1);
expect(observerBFn).toHaveBeenCalledWith('B2');
});
it('should not fail when key does not exist', () => {
expect(() =>
cleanupSubscription(queryClient, 'test-non-existing')
).not.toThrow();
});
});