|
3 | 3 | */
|
4 | 4 | /* eslint-disable @typescript-eslint/no-explicit-any */
|
5 | 5 | /* eslint-disable @typescript-eslint/ban-ts-comment */
|
6 |
| -import { QueryClient, QueryClientProvider } from '@tanstack/react-query-v5'; |
| 6 | +import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query-v5'; |
7 | 7 | import { act, renderHook, waitFor } from '@testing-library/react';
|
8 | 8 | import nock from 'nock';
|
9 | 9 | import React from 'react';
|
@@ -863,4 +863,69 @@ describe('Tanstack Query React Hooks V5 Test', () => {
|
863 | 863 | expect(cacheData[0].name).toBe('foohooray');
|
864 | 864 | });
|
865 | 865 | });
|
| 866 | + |
| 867 | + it('optimistic update mixed with non-zenstack queries', async () => { |
| 868 | + const { queryClient, wrapper } = createWrapper(); |
| 869 | + |
| 870 | + // non-zenstack query |
| 871 | + const { result: myQueryResult } = renderHook( |
| 872 | + () => useQuery({ queryKey: ['myQuery'], queryFn: () => ({ data: 'myData' }) }), |
| 873 | + { |
| 874 | + wrapper, |
| 875 | + } |
| 876 | + ); |
| 877 | + await waitFor(() => { |
| 878 | + expect(myQueryResult.current.data).toEqual({ data: 'myData' }); |
| 879 | + }); |
| 880 | + |
| 881 | + const data: any[] = []; |
| 882 | + |
| 883 | + nock(makeUrl('User', 'findMany')) |
| 884 | + .get(/.*/) |
| 885 | + .reply(200, () => { |
| 886 | + console.log('Querying data:', JSON.stringify(data)); |
| 887 | + return { data }; |
| 888 | + }) |
| 889 | + .persist(); |
| 890 | + |
| 891 | + const { result } = renderHook( |
| 892 | + () => useModelQuery('User', makeUrl('User', 'findMany'), undefined, { optimisticUpdate: true }), |
| 893 | + { |
| 894 | + wrapper, |
| 895 | + } |
| 896 | + ); |
| 897 | + await waitFor(() => { |
| 898 | + expect(result.current.data).toHaveLength(0); |
| 899 | + }); |
| 900 | + |
| 901 | + nock(makeUrl('User', 'create')) |
| 902 | + .post(/.*/) |
| 903 | + .reply(200, () => { |
| 904 | + console.log('Not mutating data'); |
| 905 | + return { data: null }; |
| 906 | + }); |
| 907 | + |
| 908 | + const { result: mutationResult } = renderHook( |
| 909 | + () => |
| 910 | + useModelMutation('User', 'POST', makeUrl('User', 'create'), modelMeta, { |
| 911 | + optimisticUpdate: true, |
| 912 | + invalidateQueries: false, |
| 913 | + }), |
| 914 | + { |
| 915 | + wrapper, |
| 916 | + } |
| 917 | + ); |
| 918 | + |
| 919 | + act(() => mutationResult.current.mutate({ data: { name: 'foo' } })); |
| 920 | + |
| 921 | + await waitFor(() => { |
| 922 | + const cacheData: any = queryClient.getQueryData( |
| 923 | + getQueryKey('User', 'findMany', undefined, { infinite: false, optimisticUpdate: true }) |
| 924 | + ); |
| 925 | + expect(cacheData).toHaveLength(1); |
| 926 | + expect(cacheData[0].$optimistic).toBe(true); |
| 927 | + expect(cacheData[0].id).toBeTruthy(); |
| 928 | + expect(cacheData[0].name).toBe('foo'); |
| 929 | + }); |
| 930 | + }); |
866 | 931 | });
|
0 commit comments