@data-client/vue 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +2 -6
  2. package/dist/index.js +145 -0
  3. package/dist/index.umd.min.js +1 -1
  4. package/lib/consumers/index.d.ts +4 -0
  5. package/lib/consumers/index.d.ts.map +1 -1
  6. package/lib/consumers/index.js +5 -1
  7. package/lib/consumers/useDebounce.d.ts +16 -0
  8. package/lib/consumers/useDebounce.d.ts.map +1 -0
  9. package/lib/consumers/useDebounce.js +50 -0
  10. package/lib/consumers/useFetch.d.ts +10 -0
  11. package/lib/consumers/useFetch.d.ts.map +1 -0
  12. package/lib/consumers/useFetch.js +41 -0
  13. package/lib/consumers/useLive.d.ts +13 -0
  14. package/lib/consumers/useLive.d.ts.map +1 -0
  15. package/lib/consumers/useLive.js +17 -0
  16. package/lib/consumers/useLoading.d.ts +18 -0
  17. package/lib/consumers/useLoading.d.ts.map +1 -0
  18. package/lib/consumers/useLoading.js +44 -0
  19. package/lib/index.js +1 -4
  20. package/node.mjs +1 -0
  21. package/package.json +1 -19
  22. package/src/__tests__/useDebounce.web.ts +264 -0
  23. package/src/__tests__/useFetch.web.ts +200 -0
  24. package/src/__tests__/useLive.web.ts +162 -0
  25. package/src/__tests__/useLoading.web.ts +238 -0
  26. package/src/consumers/index.ts +4 -0
  27. package/src/consumers/useDebounce.ts +78 -0
  28. package/src/consumers/useFetch.ts +80 -0
  29. package/src/consumers/useLive.ts +64 -0
  30. package/src/consumers/useLoading.ts +47 -0
  31. package/src/index.ts +0 -3
  32. package/ts3.4/consumers/index.d.ts +4 -0
  33. package/ts3.4/consumers/useDebounce.d.ts +19 -0
  34. package/ts3.4/consumers/useFetch.d.ts +16 -0
  35. package/ts3.4/consumers/useLive.d.ts +19 -0
  36. package/ts3.4/consumers/useLoading.d.ts +22 -0
  37. package/lib/components/DataProvider.d.ts +0 -11
  38. package/lib/components/DataProvider.d.ts.map +0 -1
  39. package/lib/components/DataProvider.js +0 -18
  40. package/src/components/DataProvider.ts +0 -26
  41. package/ts3.4/components/DataProvider.d.ts +0 -11
package/lib/index.js CHANGED
@@ -1,8 +1,5 @@
1
- // Vue Data Client - Coming Soon
2
- // This package will provide Vue 3 composables for @data-client/core
3
-
4
1
  export { Controller, ExpiryStatus, actionTypes } from '@data-client/core';
5
2
  export * from './consumers/index.js';
6
3
  export * from './providers/index.js';
7
4
  export * from './managers/index.js';
8
- //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDb250cm9sbGVyIiwiRXhwaXJ5U3RhdHVzIiwiYWN0aW9uVHlwZXMiXSwic291cmNlcyI6WyIuLi9zcmMvaW5kZXgudHMiXSwic291cmNlc0NvbnRlbnQiOlsiLy8gVnVlIERhdGEgQ2xpZW50IC0gQ29taW5nIFNvb25cbi8vIFRoaXMgcGFja2FnZSB3aWxsIHByb3ZpZGUgVnVlIDMgY29tcG9zYWJsZXMgZm9yIEBkYXRhLWNsaWVudC9jb3JlXG5cbmV4cG9ydCB7IENvbnRyb2xsZXIsIEV4cGlyeVN0YXR1cywgYWN0aW9uVHlwZXMgfSBmcm9tICdAZGF0YS1jbGllbnQvY29yZSc7XG5leHBvcnQgdHlwZSB7XG4gIEVuZHBvaW50RXh0cmFPcHRpb25zLFxuICBGZXRjaEZ1bmN0aW9uLFxuICBSZXNvbHZlVHlwZSxcbiAgRW5kcG9pbnRJbnRlcmZhY2UsXG4gIEVudGl0eUludGVyZmFjZSxcbiAgUXVlcnlhYmxlLFxuICBTY2hlbWFBcmdzLFxuICBTY2hlbWEsXG4gIFNjaGVtYUNsYXNzLFxuICBEZW5vcm1hbGl6ZU51bGxhYmxlLFxuICBEZW5vcm1hbGl6ZSxcbiAgTm9ybWFsaXplLFxuICBOb3JtYWxpemVOdWxsYWJsZSxcbiAgRmV0Y2hBY3Rpb24sXG4gIEludmFsaWRhdGVBY3Rpb24s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gsXG59IGZyb20gJ0BkYXRhLWNsaWVudC9jb3JlJztcblxuZXhwb3J0ICogZnJvbSAnLi9jb25zdW1lcnMvaW5kZXguanMnO1xuZXhwb3J0ICogZnJvbSAnLi9wcm92aWRlcnMvaW5kZXguanMnO1xuZXhwb3J0ICogZnJvbSAnLi9tYW5hZ2Vycy9pbmRleC5qcyc7XG4iXSwibWFwcGluZ3MiOiJBQUFBLFNBQVNBLFVBQVUsRUFBRUMsWUFBWSxFQUFFQyxXQUFXLFFBQVEsbUJBQW1CO0FBMEN6RSxjQUFjLHNCQUFzQjtBQUNwQyxjQUFjLHNCQUFzQjtBQUNwQyxjQUFjLHFCQUFxQiIsImlnbm9yZUxpc3QiOltdfQ==
package/node.mjs ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/index.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@data-client/vue",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "Async State Management without the Management. REST, GraphQL, SSE, Websockets, Fetch",
5
5
  "homepage": "https://dataclient.io",
6
6
  "repository": {
@@ -49,24 +49,6 @@
49
49
  "module": "lib/index.js",
50
50
  "unpkg": "dist/index.umd.min.js",
51
51
  "types": "lib/index.d.ts",
52
- "typesVersions": {
53
- ">=4.0": {
54
- "": [
55
- "lib/index.d.ts"
56
- ],
57
- "*": [
58
- "lib/index.d.ts"
59
- ]
60
- },
61
- ">=3.4": {
62
- "": [
63
- "ts3.4/index.d.ts"
64
- ],
65
- "*": [
66
- "ts3.4/index.d.ts"
67
- ]
68
- }
69
- },
70
52
  "exports": {
71
53
  ".": {
72
54
  "module": "./lib/index.js",
@@ -0,0 +1,264 @@
1
+ import { mount } from '@vue/test-utils';
2
+ import { defineComponent, h, nextTick, ref } from 'vue';
3
+
4
+ import useDebounce from '../consumers/useDebounce';
5
+
6
+ describe('vue useDebounce()', () => {
7
+ beforeEach(() => {
8
+ jest.useFakeTimers();
9
+ });
10
+
11
+ afterEach(() => {
12
+ jest.runOnlyPendingTimers();
13
+ jest.useRealTimers();
14
+ });
15
+
16
+ it('debounces value updates with correct delay', async () => {
17
+ const TestComponent = defineComponent({
18
+ name: 'TestComponent',
19
+ setup() {
20
+ const query = ref('initial');
21
+ const [debouncedQuery, isPending] = useDebounce(query, 200);
22
+
23
+ const updateQuery = (newValue: string) => {
24
+ query.value = newValue;
25
+ };
26
+
27
+ return () =>
28
+ h('div', [
29
+ h('input', {
30
+ value: query.value,
31
+ onInput: (e: any) => updateQuery(e.target.value),
32
+ 'data-testid': 'input',
33
+ }),
34
+ h('div', { 'data-testid': 'original' }, query.value),
35
+ h('div', { 'data-testid': 'debounced' }, debouncedQuery.value),
36
+ h('div', { 'data-testid': 'pending' }, isPending.value.toString()),
37
+ ]);
38
+ },
39
+ });
40
+
41
+ const wrapper = mount(TestComponent);
42
+
43
+ // Initially, debounced value should match original
44
+ expect(wrapper.find('[data-testid="original"]').text()).toBe('initial');
45
+ expect(wrapper.find('[data-testid="debounced"]').text()).toBe('initial');
46
+ expect(wrapper.find('[data-testid="pending"]').text()).toBe('false');
47
+
48
+ // Update the input
49
+ const input = wrapper.find('[data-testid="input"]');
50
+ await input.setValue('updated');
51
+ await nextTick();
52
+
53
+ // Original should update immediately, debounced should not
54
+ expect(wrapper.find('[data-testid="original"]').text()).toBe('updated');
55
+ expect(wrapper.find('[data-testid="debounced"]').text()).toBe('initial');
56
+ expect(wrapper.find('[data-testid="pending"]').text()).toBe('true');
57
+
58
+ // Fast-forward time by less than delay
59
+ jest.advanceTimersByTime(100);
60
+ await nextTick();
61
+
62
+ // Debounced should still be old value
63
+ expect(wrapper.find('[data-testid="debounced"]').text()).toBe('initial');
64
+ expect(wrapper.find('[data-testid="pending"]').text()).toBe('true');
65
+
66
+ // Fast-forward time by remaining delay
67
+ jest.advanceTimersByTime(100);
68
+ await nextTick();
69
+
70
+ // Now debounced should update
71
+ expect(wrapper.find('[data-testid="debounced"]').text()).toBe('updated');
72
+ expect(wrapper.find('[data-testid="pending"]').text()).toBe('false');
73
+ });
74
+
75
+ it('cancels previous timeout when value changes rapidly', async () => {
76
+ const TestComponent = defineComponent({
77
+ name: 'TestComponent',
78
+ setup() {
79
+ const query = ref('initial');
80
+ const [debouncedQuery, isPending] = useDebounce(query, 200);
81
+
82
+ const updateQuery = (newValue: string) => {
83
+ query.value = newValue;
84
+ };
85
+
86
+ return () =>
87
+ h('div', [
88
+ h('input', {
89
+ value: query.value,
90
+ onInput: (e: any) => updateQuery(e.target.value),
91
+ 'data-testid': 'input',
92
+ }),
93
+ h('div', { 'data-testid': 'debounced' }, debouncedQuery.value),
94
+ h('div', { 'data-testid': 'pending' }, isPending.value.toString()),
95
+ ]);
96
+ },
97
+ });
98
+
99
+ const wrapper = mount(TestComponent);
100
+
101
+ // Rapid updates
102
+ const input = wrapper.find('[data-testid="input"]');
103
+ await input.setValue('first');
104
+ await nextTick();
105
+
106
+ expect(wrapper.find('[data-testid="pending"]').text()).toBe('true');
107
+
108
+ // Fast-forward partway
109
+ jest.advanceTimersByTime(100);
110
+
111
+ // Another update before timeout
112
+ await input.setValue('second');
113
+ await nextTick();
114
+
115
+ // Fast-forward full delay from second update
116
+ jest.advanceTimersByTime(200);
117
+ await nextTick();
118
+
119
+ // Should show the second value, not first
120
+ expect(wrapper.find('[data-testid="debounced"]').text()).toBe('second');
121
+ expect(wrapper.find('[data-testid="pending"]').text()).toBe('false');
122
+ });
123
+
124
+ it('respects updatable parameter', async () => {
125
+ const TestComponent = defineComponent({
126
+ name: 'TestComponent',
127
+ setup() {
128
+ const query = ref('initial');
129
+ const updatable = ref(true);
130
+ const [debouncedQuery, isPending] = useDebounce(query, 200, updatable);
131
+
132
+ const updateQuery = (newValue: string) => {
133
+ query.value = newValue;
134
+ };
135
+
136
+ const toggleUpdatable = () => {
137
+ updatable.value = !updatable.value;
138
+ };
139
+
140
+ return () =>
141
+ h('div', [
142
+ h('input', {
143
+ value: query.value,
144
+ onInput: (e: any) => updateQuery(e.target.value),
145
+ 'data-testid': 'input',
146
+ }),
147
+ h(
148
+ 'button',
149
+ {
150
+ onClick: toggleUpdatable,
151
+ 'data-testid': 'toggle',
152
+ },
153
+ `Updatable: ${updatable.value}`,
154
+ ),
155
+ h('div', { 'data-testid': 'debounced' }, debouncedQuery.value),
156
+ h('div', { 'data-testid': 'pending' }, isPending.value.toString()),
157
+ ]);
158
+ },
159
+ });
160
+
161
+ const wrapper = mount(TestComponent);
162
+
163
+ // Disable updates
164
+ await wrapper.find('[data-testid="toggle"]').trigger('click');
165
+ await nextTick();
166
+
167
+ // Update input
168
+ await wrapper.find('[data-testid="input"]').setValue('disabled');
169
+ await nextTick();
170
+
171
+ // Should not be pending since updates are disabled
172
+ expect(wrapper.find('[data-testid="pending"]').text()).toBe('false');
173
+
174
+ // Fast-forward time
175
+ jest.advanceTimersByTime(300);
176
+ await nextTick();
177
+
178
+ // Debounced value should not have updated
179
+ expect(wrapper.find('[data-testid="debounced"]').text()).toBe('initial');
180
+ });
181
+
182
+ it('cleans up timeout on unmount', async () => {
183
+ const clearTimeoutSpy = jest.spyOn(global, 'clearTimeout');
184
+
185
+ const TestComponent = defineComponent({
186
+ name: 'TestComponent',
187
+ setup() {
188
+ const query = ref('initial');
189
+ const [debouncedQuery] = useDebounce(query, 200);
190
+
191
+ const updateQuery = (newValue: string) => {
192
+ query.value = newValue;
193
+ };
194
+
195
+ return () =>
196
+ h('div', [
197
+ h('input', {
198
+ value: query.value,
199
+ onInput: (e: any) => updateQuery(e.target.value),
200
+ 'data-testid': 'input',
201
+ }),
202
+ h('div', { 'data-testid': 'debounced' }, debouncedQuery.value),
203
+ ]);
204
+ },
205
+ });
206
+
207
+ const wrapper = mount(TestComponent);
208
+
209
+ // Update input to trigger timeout
210
+ await wrapper.find('[data-testid="input"]').setValue('will unmount');
211
+ await nextTick();
212
+
213
+ // Unmount component
214
+ wrapper.unmount();
215
+
216
+ // Should have called clearTimeout
217
+ expect(clearTimeoutSpy).toHaveBeenCalled();
218
+
219
+ clearTimeoutSpy.mockRestore();
220
+ });
221
+
222
+ it('works with reactive refs as input', async () => {
223
+ const TestComponent = defineComponent({
224
+ name: 'TestComponent',
225
+ setup() {
226
+ const query = ref('initial');
227
+ const [debouncedQuery, isPending] = useDebounce(query, 200);
228
+
229
+ const updateQuery = (newValue: string) => {
230
+ query.value = newValue;
231
+ };
232
+
233
+ return () =>
234
+ h('div', [
235
+ h(
236
+ 'button',
237
+ {
238
+ onClick: () => updateQuery('reactive'),
239
+ 'data-testid': 'button',
240
+ },
241
+ 'Update',
242
+ ),
243
+ h('div', { 'data-testid': 'debounced' }, debouncedQuery.value),
244
+ h('div', { 'data-testid': 'pending' }, isPending.value.toString()),
245
+ ]);
246
+ },
247
+ });
248
+
249
+ const wrapper = mount(TestComponent);
250
+
251
+ // Click to update
252
+ await wrapper.find('[data-testid="button"]').trigger('click');
253
+ await nextTick();
254
+
255
+ expect(wrapper.find('[data-testid="pending"]').text()).toBe('true');
256
+
257
+ // Fast-forward time
258
+ jest.advanceTimersByTime(200);
259
+ await nextTick();
260
+
261
+ expect(wrapper.find('[data-testid="debounced"]').text()).toBe('reactive');
262
+ expect(wrapper.find('[data-testid="pending"]').text()).toBe('false');
263
+ });
264
+ });
@@ -0,0 +1,200 @@
1
+ import { mount } from '@vue/test-utils';
2
+ import nock from 'nock';
3
+ import { defineComponent, h, nextTick } from 'vue';
4
+
5
+ // Reuse the same endpoints/fixtures used by the React tests
6
+ import {
7
+ CoolerArticleResource,
8
+ StaticArticleResource,
9
+ } from '../../../../__tests__/new';
10
+ // Minimal shared fixture (copied from React test fixtures)
11
+ const payload = {
12
+ id: 5,
13
+ title: 'hi ho',
14
+ content: 'whatever',
15
+ tags: ['a', 'best', 'react'],
16
+ };
17
+ import useFetch from '../consumers/useFetch';
18
+ import { provideDataClient } from '../providers/provideDataClient';
19
+
20
+ async function flush() {
21
+ await Promise.resolve();
22
+ await nextTick();
23
+ await new Promise(resolve => setTimeout(resolve, 0));
24
+ }
25
+
26
+ async function flushUntil(wrapper: any, predicate: () => boolean, tries = 100) {
27
+ for (let i = 0; i < tries; i++) {
28
+ if (predicate()) return;
29
+ await flush();
30
+ }
31
+ }
32
+
33
+ describe('vue useFetch()', () => {
34
+ let mynock: nock.Scope;
35
+ beforeAll(() => {
36
+ nock(/.*/)
37
+ .persist()
38
+ .defaultReplyHeaders({
39
+ 'Access-Control-Allow-Origin': '*',
40
+ 'Access-Control-Allow-Headers': 'Access-Token',
41
+ 'Content-Type': 'application/json',
42
+ })
43
+ .options(/.*/)
44
+ .reply(200);
45
+ });
46
+ beforeEach(() => {
47
+ mynock = nock(/.*/).defaultReplyHeaders({
48
+ 'Access-Control-Allow-Origin': '*',
49
+ 'Access-Control-Allow-Headers': 'Access-Token',
50
+ 'Content-Type': 'application/json',
51
+ });
52
+ });
53
+
54
+ afterEach(() => {
55
+ nock.cleanAll();
56
+ });
57
+
58
+ const ProvideWrapper = defineComponent({
59
+ name: 'ProvideWrapper',
60
+ setup(_props, { slots, expose }) {
61
+ const { controller } = provideDataClient();
62
+ expose({ controller });
63
+ return () => (slots.default ? slots.default() : h('div'));
64
+ },
65
+ });
66
+
67
+ it('should dispatch singles', async () => {
68
+ const fetchMock = jest.fn(() => payload);
69
+ mynock.get(`/article-cooler/${payload.id}`).reply(200, fetchMock);
70
+
71
+ const Comp = defineComponent({
72
+ name: 'FetchTester',
73
+ setup() {
74
+ const p = useFetch(CoolerArticleResource.get, { id: payload.id });
75
+ return () => h('div', { class: 'root' }, String(!!p));
76
+ },
77
+ });
78
+
79
+ const wrapper = mount(ProvideWrapper, {
80
+ slots: { default: () => h(Comp) },
81
+ });
82
+
83
+ // Wait for the fetch to happen
84
+ await flushUntil(wrapper, () => fetchMock.mock.calls.length > 0);
85
+ expect(fetchMock).toHaveBeenCalledTimes(1);
86
+ });
87
+
88
+ it('should not dispatch with null params, then dispatch after set', async () => {
89
+ const fetchMock = jest.fn(() => payload);
90
+ mynock.get(`/article-cooler/${payload.id}`).reply(200, fetchMock);
91
+
92
+ let params: any = null;
93
+ const Comp = defineComponent({
94
+ name: 'FetchTesterNull',
95
+ setup() {
96
+ // reactive params via closure re-render with slot remount
97
+ useFetch(CoolerArticleResource.get as any, params);
98
+ return () => h('div');
99
+ },
100
+ });
101
+
102
+ const wrapper = mount(ProvideWrapper, {
103
+ slots: { default: () => h(Comp) },
104
+ });
105
+ await flush();
106
+ expect(fetchMock).toHaveBeenCalledTimes(0);
107
+
108
+ // change params and remount child to re-run setup
109
+ params = { id: payload.id };
110
+ wrapper.unmount();
111
+ const wrapper2 = mount(ProvideWrapper, {
112
+ slots: { default: () => h(Comp) },
113
+ });
114
+ await flushUntil(wrapper2, () => fetchMock.mock.calls.length > 0);
115
+ expect(fetchMock).toHaveBeenCalledTimes(1);
116
+ });
117
+
118
+ it('should respect expiry and not refetch when fresh', async () => {
119
+ const fetchMock = jest.fn(() => payload);
120
+ mynock.get(`/article-cooler/${payload.id}`).reply(200, fetchMock);
121
+
122
+ const Child = defineComponent({
123
+ name: 'FetchChild',
124
+ setup() {
125
+ useFetch(CoolerArticleResource.get, { id: payload.id });
126
+ return () => h('div');
127
+ },
128
+ });
129
+
130
+ const Parent = defineComponent({
131
+ name: 'Parent',
132
+ setup(_props, { expose }) {
133
+ const { controller } = provideDataClient();
134
+ let idx = 0;
135
+ const remount = () => {
136
+ idx++;
137
+ };
138
+ expose({ controller, remount });
139
+ return () => h('div', [h(Child, { key: idx })]);
140
+ },
141
+ });
142
+
143
+ const wrapper = mount(Parent);
144
+ await flushUntil(wrapper, () => fetchMock.mock.calls.length > 0);
145
+ expect(fetchMock).toHaveBeenCalledTimes(1);
146
+
147
+ // Remount child inside same provider should not refetch while data is fresh
148
+ (wrapper.vm as any).remount();
149
+ await flush();
150
+ expect(fetchMock).toHaveBeenCalledTimes(1);
151
+ });
152
+
153
+ it('should dispatch with resource and endpoint expiry overrides', async () => {
154
+ const mock1 = jest.fn(() => payload);
155
+ const mock2 = jest.fn(() => payload);
156
+ const mock3 = jest.fn(() => payload);
157
+
158
+ mynock
159
+ .get(`/article-static/${payload.id}`)
160
+ .reply(200, mock1)
161
+ .get(`/article-static/${payload.id}`)
162
+ .reply(200, mock2)
163
+ .get(`/article-static/${payload.id}`)
164
+ .reply(200, mock3);
165
+
166
+ const Comp1 = defineComponent({
167
+ name: 'FetchStaticGet',
168
+ setup() {
169
+ useFetch(StaticArticleResource.get, { id: payload.id });
170
+ return () => h('div');
171
+ },
172
+ });
173
+ const Comp2 = defineComponent({
174
+ name: 'FetchStaticLong',
175
+ setup() {
176
+ useFetch(StaticArticleResource.longLiving, { id: payload.id });
177
+ return () => h('div');
178
+ },
179
+ });
180
+ const Comp3 = defineComponent({
181
+ name: 'FetchStaticNeverRetry',
182
+ setup() {
183
+ useFetch(StaticArticleResource.neverRetryOnError, { id: payload.id });
184
+ return () => h('div');
185
+ },
186
+ });
187
+
188
+ const w1 = mount(ProvideWrapper, { slots: { default: () => h(Comp1) } });
189
+ await flushUntil(w1, () => mock1.mock.calls.length > 0);
190
+ expect(mock1).toHaveBeenCalled();
191
+
192
+ const w2 = mount(ProvideWrapper, { slots: { default: () => h(Comp2) } });
193
+ await flushUntil(w2, () => mock2.mock.calls.length > 0);
194
+ expect(mock2).toHaveBeenCalled();
195
+
196
+ const w3 = mount(ProvideWrapper, { slots: { default: () => h(Comp3) } });
197
+ await flushUntil(w3, () => mock3.mock.calls.length > 0);
198
+ expect(mock3).toHaveBeenCalled();
199
+ });
200
+ });
@@ -0,0 +1,162 @@
1
+ import { mount } from '@vue/test-utils';
2
+ import nock from 'nock';
3
+ import { defineComponent, h, nextTick, Suspense } from 'vue';
4
+
5
+ // Reuse the same endpoints/fixtures used by the React tests
6
+ import { CoolerArticleResource } from '../../../../__tests__/new';
7
+ // Minimal shared fixture (copied from React test fixtures)
8
+ const payload = {
9
+ id: 5,
10
+ title: 'hi ho',
11
+ content: 'whatever',
12
+ tags: ['a', 'best', 'react'],
13
+ };
14
+ import useLive from '../consumers/useLive';
15
+ import { provideDataClient } from '../providers/provideDataClient';
16
+
17
+ describe('vue useLive()', () => {
18
+ async function flushUntil(
19
+ wrapper: any,
20
+ predicate: () => boolean,
21
+ tries = 100,
22
+ ) {
23
+ for (let i = 0; i < tries; i++) {
24
+ if (predicate()) return;
25
+ await Promise.resolve();
26
+ await nextTick();
27
+ await new Promise(resolve => setTimeout(resolve, 0));
28
+ }
29
+ }
30
+
31
+ beforeAll(() => {
32
+ nock(/.*/)
33
+ .persist()
34
+ .defaultReplyHeaders({
35
+ 'Access-Control-Allow-Origin': '*',
36
+ 'Access-Control-Allow-Headers': 'Access-Token',
37
+ 'Content-Type': 'application/json',
38
+ })
39
+ .options(/.*/)
40
+ .reply(200)
41
+ .get(`/article-cooler/${payload.id}`)
42
+ .reply(200, payload)
43
+ .put(`/article-cooler/${payload.id}`)
44
+ .reply(200, (uri, requestBody: any) => ({
45
+ ...payload,
46
+ ...requestBody,
47
+ }));
48
+ });
49
+
50
+ afterAll(() => {
51
+ nock.cleanAll();
52
+ });
53
+
54
+ const ArticleComp = defineComponent({
55
+ name: 'ArticleComp',
56
+ async setup() {
57
+ const article = await useLive(CoolerArticleResource.get, {
58
+ id: payload.id,
59
+ });
60
+ return () =>
61
+ h('div', [
62
+ h('h3', (article as any).value.title),
63
+ h('p', (article as any).value.content),
64
+ ]);
65
+ },
66
+ });
67
+
68
+ const ProvideWrapper = defineComponent({
69
+ name: 'ProvideWrapper',
70
+ setup(_props, { slots, expose }) {
71
+ const { controller } = provideDataClient();
72
+ expose({ controller });
73
+ return () =>
74
+ h(
75
+ Suspense,
76
+ {},
77
+ {
78
+ default: () => (slots.default ? slots.default() : h(ArticleComp)),
79
+ fallback: () => h('div', { class: 'fallback' }, 'Loading'),
80
+ },
81
+ );
82
+ },
83
+ });
84
+
85
+ it('suspends on empty store, then renders after fetch resolves', async () => {
86
+ const wrapper = mount(ProvideWrapper, {
87
+ slots: { default: () => h(ArticleComp) },
88
+ });
89
+
90
+ // Initially should render fallback while Suspense is pending
91
+ expect(wrapper.find('.fallback').exists()).toBe(true);
92
+
93
+ // Flush pending promises/ticks until content renders
94
+ await flushUntil(wrapper, () => wrapper.find('h3').exists());
95
+
96
+ const title = wrapper.find('h3');
97
+ const content = wrapper.find('p');
98
+ expect(title.exists()).toBe(true);
99
+ expect(content.exists()).toBe(true);
100
+ expect(title.text()).toBe(payload.title);
101
+ expect(content.text()).toBe(payload.content);
102
+ });
103
+
104
+ it('re-renders when controller.setResponse() updates data', async () => {
105
+ const wrapper = mount(ProvideWrapper, {
106
+ slots: { default: () => h(ArticleComp) },
107
+ });
108
+ // Wait for initial render
109
+ await flushUntil(wrapper, () => wrapper.find('h3').exists());
110
+
111
+ // Verify initial values
112
+ expect(wrapper.find('h3').text()).toBe(payload.title);
113
+ expect(wrapper.find('p').text()).toBe(payload.content);
114
+
115
+ // Update the store using controller.setResponse
116
+ const exposed: any = wrapper.vm as any;
117
+ const newTitle = payload.title + ' updated';
118
+ const newContent = (payload as any).content + ' v2';
119
+ exposed.controller.setResponse(
120
+ CoolerArticleResource.get,
121
+ { id: payload.id },
122
+ { ...payload, title: newTitle, content: newContent },
123
+ );
124
+
125
+ await flushUntil(wrapper, () => wrapper.find('h3').text() === newTitle);
126
+
127
+ expect(wrapper.find('h3').text()).toBe(newTitle);
128
+ expect(wrapper.find('p').text()).toBe(newContent);
129
+ });
130
+
131
+ it('stays subscribed and reacts to server updates', async () => {
132
+ // This test verifies that useLive includes subscription behavior
133
+ const wrapper = mount(ProvideWrapper, {
134
+ slots: { default: () => h(ArticleComp) },
135
+ });
136
+
137
+ // Wait for initial render
138
+ await flushUntil(wrapper, () => wrapper.find('h3').exists());
139
+
140
+ // Verify initial values
141
+ expect(wrapper.find('h3').text()).toBe(payload.title);
142
+
143
+ const exposed: any = wrapper.vm as any;
144
+
145
+ // Simulate a server update that would trigger subscription
146
+ const updatedTitle = payload.title + ' live updated';
147
+ const updatedContent = payload.content + ' live updated';
148
+
149
+ // Use controller.fetch to simulate an update that would come from subscription
150
+ await exposed.controller.fetch(
151
+ CoolerArticleResource.update,
152
+ { id: payload.id },
153
+ { title: updatedTitle, content: updatedContent },
154
+ );
155
+
156
+ // Wait for re-render with new data
157
+ await flushUntil(wrapper, () => wrapper.find('h3').text() === updatedTitle);
158
+
159
+ expect(wrapper.find('h3').text()).toBe(updatedTitle);
160
+ expect(wrapper.find('p').text()).toBe(updatedContent);
161
+ });
162
+ });