@data-client/vue 0.0.2 → 0.0.3

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.
@@ -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,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
+ });
@@ -0,0 +1,238 @@
1
+ import { mount } from '@vue/test-utils';
2
+ import { defineComponent, h, nextTick } from 'vue';
3
+
4
+ import useLoading from '../consumers/useLoading';
5
+
6
+ describe('vue useLoading()', () => {
7
+ async function flushUntil(
8
+ wrapper: any,
9
+ predicate: () => boolean,
10
+ tries = 100,
11
+ ) {
12
+ for (let i = 0; i < tries; i++) {
13
+ if (predicate()) return;
14
+ await Promise.resolve();
15
+ await nextTick();
16
+ await new Promise(resolve => setTimeout(resolve, 0));
17
+ }
18
+ }
19
+
20
+ it('tracks loading state for async functions', async () => {
21
+ let resolvePromise: (value: string) => void;
22
+ const mockAsyncFunction = jest.fn(
23
+ () =>
24
+ new Promise<string>(resolve => {
25
+ resolvePromise = resolve;
26
+ }),
27
+ );
28
+
29
+ const TestComponent = defineComponent({
30
+ name: 'TestComponent',
31
+ setup() {
32
+ const [wrappedFunction, loading, error] = useLoading(mockAsyncFunction);
33
+
34
+ const handleClick = async () => {
35
+ await wrappedFunction();
36
+ };
37
+
38
+ return () =>
39
+ h('div', [
40
+ h(
41
+ 'button',
42
+ {
43
+ onClick: handleClick,
44
+ 'data-testid': 'test-button',
45
+ },
46
+ loading.value ? 'Loading...' : 'Click me',
47
+ ),
48
+ h('div', { 'data-testid': 'error' }, error.value?.message || ''),
49
+ h('div', { 'data-testid': 'loading' }, loading.value.toString()),
50
+ ]);
51
+ },
52
+ });
53
+
54
+ const wrapper = mount(TestComponent);
55
+
56
+ // Initially not loading
57
+ expect(wrapper.find('[data-testid="loading"]').text()).toBe('false');
58
+ expect(wrapper.find('[data-testid="test-button"]').text()).toBe('Click me');
59
+
60
+ // Click to trigger loading
61
+ await wrapper.find('[data-testid="test-button"]').trigger('click');
62
+ await nextTick();
63
+
64
+ // Should be loading
65
+ expect(wrapper.find('[data-testid="loading"]').text()).toBe('true');
66
+ expect(wrapper.find('[data-testid="test-button"]').text()).toBe(
67
+ 'Loading...',
68
+ );
69
+
70
+ // Resolve the promise
71
+ resolvePromise!('success');
72
+ await flushUntil(
73
+ wrapper,
74
+ () => wrapper.find('[data-testid="loading"]').text() === 'false',
75
+ );
76
+
77
+ // Should not be loading anymore
78
+ expect(wrapper.find('[data-testid="loading"]').text()).toBe('false');
79
+ expect(wrapper.find('[data-testid="test-button"]').text()).toBe('Click me');
80
+ expect(mockAsyncFunction).toHaveBeenCalledTimes(1);
81
+ });
82
+
83
+ it('handles errors from async functions', async () => {
84
+ const testError = new Error('Test error');
85
+ const mockAsyncFunction = jest.fn(() => Promise.reject(testError));
86
+
87
+ const TestComponent = defineComponent({
88
+ name: 'TestComponent',
89
+ setup() {
90
+ const [wrappedFunction, loading, error] = useLoading(mockAsyncFunction);
91
+
92
+ const handleClick = async () => {
93
+ await wrappedFunction();
94
+ };
95
+
96
+ return () =>
97
+ h('div', [
98
+ h(
99
+ 'button',
100
+ {
101
+ onClick: handleClick,
102
+ 'data-testid': 'test-button',
103
+ },
104
+ 'Click me',
105
+ ),
106
+ h('div', { 'data-testid': 'error' }, error.value?.message || ''),
107
+ h('div', { 'data-testid': 'loading' }, loading.value.toString()),
108
+ ]);
109
+ },
110
+ });
111
+
112
+ const wrapper = mount(TestComponent);
113
+
114
+ // Click to trigger error
115
+ await wrapper.find('[data-testid="test-button"]').trigger('click');
116
+ await flushUntil(
117
+ wrapper,
118
+ () => wrapper.find('[data-testid="error"]').text() === 'Test error',
119
+ );
120
+
121
+ // Should capture the error
122
+ expect(wrapper.find('[data-testid="error"]').text()).toBe('Test error');
123
+ expect(wrapper.find('[data-testid="loading"]').text()).toBe('false');
124
+ expect(mockAsyncFunction).toHaveBeenCalledTimes(1);
125
+ });
126
+
127
+ it('does not update loading state after component unmount', async () => {
128
+ let resolvePromise: (value: string) => void;
129
+ const mockAsyncFunction = jest.fn(
130
+ () =>
131
+ new Promise<string>(resolve => {
132
+ resolvePromise = resolve;
133
+ }),
134
+ );
135
+
136
+ const TestComponent = defineComponent({
137
+ name: 'TestComponent',
138
+ setup() {
139
+ const [wrappedFunction, loading] = useLoading(mockAsyncFunction);
140
+
141
+ const handleClick = async () => {
142
+ await wrappedFunction();
143
+ };
144
+
145
+ return () =>
146
+ h('div', [
147
+ h(
148
+ 'button',
149
+ {
150
+ onClick: handleClick,
151
+ 'data-testid': 'test-button',
152
+ },
153
+ 'Click me',
154
+ ),
155
+ h('div', { 'data-testid': 'loading' }, loading.value.toString()),
156
+ ]);
157
+ },
158
+ });
159
+
160
+ const wrapper = mount(TestComponent);
161
+
162
+ // Click to trigger loading
163
+ await wrapper.find('[data-testid="test-button"]').trigger('click');
164
+ await nextTick();
165
+
166
+ // Should be loading
167
+ expect(wrapper.find('[data-testid="loading"]').text()).toBe('true');
168
+
169
+ // Unmount component before resolving
170
+ wrapper.unmount();
171
+
172
+ // Resolve the promise after unmount
173
+ resolvePromise!('success');
174
+ await new Promise(resolve => setTimeout(resolve, 0));
175
+
176
+ // Component should be unmounted, no errors should occur
177
+ expect(mockAsyncFunction).toHaveBeenCalledTimes(1);
178
+ });
179
+
180
+ it('clears error on subsequent calls', async () => {
181
+ const testError = new Error('Test error');
182
+ let shouldError = true;
183
+ const mockAsyncFunction = jest.fn(() => {
184
+ if (shouldError) {
185
+ return Promise.reject(testError);
186
+ }
187
+ return Promise.resolve('success');
188
+ });
189
+
190
+ const TestComponent = defineComponent({
191
+ name: 'TestComponent',
192
+ setup() {
193
+ const [wrappedFunction, loading, error] = useLoading(mockAsyncFunction);
194
+
195
+ const handleClick = async () => {
196
+ await wrappedFunction();
197
+ };
198
+
199
+ return () =>
200
+ h('div', [
201
+ h(
202
+ 'button',
203
+ {
204
+ onClick: handleClick,
205
+ 'data-testid': 'test-button',
206
+ },
207
+ 'Click me',
208
+ ),
209
+ h('div', { 'data-testid': 'error' }, error.value?.message || ''),
210
+ h('div', { 'data-testid': 'loading' }, loading.value.toString()),
211
+ ]);
212
+ },
213
+ });
214
+
215
+ const wrapper = mount(TestComponent);
216
+
217
+ // First call - should error
218
+ await wrapper.find('[data-testid="test-button"]').trigger('click');
219
+ await flushUntil(
220
+ wrapper,
221
+ () => wrapper.find('[data-testid="error"]').text() === 'Test error',
222
+ );
223
+
224
+ expect(wrapper.find('[data-testid="error"]').text()).toBe('Test error');
225
+
226
+ // Second call - should succeed and clear error
227
+ shouldError = false;
228
+ await wrapper.find('[data-testid="test-button"]').trigger('click');
229
+ await flushUntil(
230
+ wrapper,
231
+ () => wrapper.find('[data-testid="error"]').text() === '',
232
+ );
233
+
234
+ expect(wrapper.find('[data-testid="error"]').text()).toBe('');
235
+ expect(wrapper.find('[data-testid="loading"]').text()).toBe('false');
236
+ expect(mockAsyncFunction).toHaveBeenCalledTimes(2);
237
+ });
238
+ });
@@ -1,4 +1,7 @@
1
1
  export { default as useSuspense } from './useSuspense.js';
2
2
  export { default as useSubscription } from './useSubscription.js';
3
3
  export { default as useQuery } from './useQuery.js';
4
+ export { default as useLive } from './useLive.js';
5
+ export { default as useLoading } from './useLoading.js';
6
+ export { default as useDebounce } from './useDebounce.js';
4
7
  export { useController as useController } from '../context.js';