Open History to see the last commit
1import { RuleTester } from '@typescript-eslint/rule-tester'
2import combinate from 'combinate'
3β
4import {
5 checkedProperties,
6 infiniteQueryFunctions,
7} from '../rules/infinite-query-property-order/constants'
8import {
9 name,
10 rule,
11} from '../rules/infinite-query-property-order/infinite-query-property-order.rule'
12import {
13 generateInterleavedCombinations,
14 generatePartialCombinations,
15 generatePermutations,
16 normalizeIndent,
17} from './test-utils'
18import type { InfiniteQueryFunctions } from '../rules/infinite-query-property-order/constants'
19β
20const ruleTester = new RuleTester()
21β
22type CheckedProperties = (typeof checkedProperties)[number]
23const orderIndependentProps = [
24 'queryKey',
25 '...objectExpressionSpread',
26 '...callExpressionSpread',
27 '...memberCallExpressionSpread',
28] as const
29type OrderIndependentProps = (typeof orderIndependentProps)[number]
30β
31interface TestCase {
32 infiniteQueryFunction: InfiniteQueryFunctions
33 properties: Array<CheckedProperties | OrderIndependentProps>
34}
35β
36const validTestMatrix = combinate({
37 infiniteQueryFunction: [...infiniteQueryFunctions],
38 properties: generatePartialCombinations(checkedProperties, 2),
39})
40β
41export function generateInvalidPermutations(
42 arr: ReadonlyArray<CheckedProperties>,
43): Array<{
44 invalid: Array<CheckedProperties>
45 valid: Array<CheckedProperties>
46}> {
47 const combinations = generatePartialCombinations(arr, 2)
48 const allPermutations: Array<{
49 invalid: Array<CheckedProperties>
50 valid: Array<CheckedProperties>
51 }> = []
52β
53 for (const combination of combinations) {
54 const permutations = generatePermutations(combination)
55 // skip the first permutation as it matches the original combination
56 const invalidPermutations = permutations.slice(1)
57β
58 if (
59 combination.includes('getNextPageParam') &&
60 combination.includes('getPreviousPageParam')
61 ) {
62 if (
63 combination.indexOf('getNextPageParam') <
64 combination.indexOf('getPreviousPageParam')
65 ) {
66 // since we ignore the relative order of 'getPreviousPageParam' and 'getNextPageParam', we skip this combination (but keep the other one where `getPreviousPageParam` is before `getNextPageParam`)
67β
68 continue
69 }
70 }
71β
72 allPermutations.push(
73 ...invalidPermutations
74 .map((p) => {
75 // ignore the relative order of 'getPreviousPageParam' and 'getNextPageParam'
76 const correctedValid = [...combination].sort((a, b) => {
77 if (
78 (a === 'getNextPageParam' && b === 'getPreviousPageParam') ||
79 (a === 'getPreviousPageParam' && b === 'getNextPageParam')
80 ) {
81 return p.indexOf(a) - p.indexOf(b)
82 }
83 return checkedProperties.indexOf(a) - checkedProperties.indexOf(b)
84 })
85 return { invalid: p, valid: correctedValid }
86 })
87 .filter(
88 ({ invalid }) =>
89 // if `getPreviousPageParam` and `getNextPageParam` are next to each other and `queryFn` is not present, we skip this invalid permutation
90 Math.abs(
91 invalid.indexOf('getNextPageParam') -
92 invalid.indexOf('getPreviousPageParam'),
93 ) !== 1,
94 ),
95 )
96 }
97β
98 return allPermutations
99}
100β
101const invalidPermutations = generateInvalidPermutations(checkedProperties)
102β
103type Interleaved = CheckedProperties | OrderIndependentProps
104const interleavedInvalidPermutations: Array<{
105 invalid: Array<Interleaved>
106 valid: Array<Interleaved>
107}> = []
108for (const invalidPermutation of invalidPermutations) {
109 const invalid = generateInterleavedCombinations(
110 invalidPermutation.invalid,
111 orderIndependentProps,
112 )
113 const valid = generateInterleavedCombinations(
114 invalidPermutation.valid,
115 orderIndependentProps,
116 )
117β
118 for (let i = 0; i < invalid.length; i++) {
119 interleavedInvalidPermutations.push({
120 invalid: invalid[i]!,
121 valid: valid[i]!,
122 })
123 }
124}
125β
126const invalidTestMatrix = combinate({
127 infiniteQueryFunction: [...infiniteQueryFunctions],
128 properties: interleavedInvalidPermutations,
129})
130β
131const callExpressionSpread = normalizeIndent`
132 ...communitiesQuery({
133 filters: {
134 ...fieldValues,
135 placementFormats: [],
136 },
137 })`
138β
139function getCode({
140 infiniteQueryFunction: infiniteQueryFunction,
141 properties,
142}: TestCase) {
143 function getPropertyCode(
144 property: CheckedProperties | OrderIndependentProps,
145 ) {
146 switch (property) {
147 case '...objectExpressionSpread':
148 return `...objectExpressionSpread`
149 case '...callExpressionSpread':
150 return callExpressionSpread
151 case '...memberCallExpressionSpread':
152 return '...myOptions.infiniteQueryOptions()'
153 case 'queryKey':
154 return `queryKey: ['projects']`
155 case 'queryFn':
156 return 'queryFn: async ({ pageParam }) => { \n await fetch(`/api/projects?cursor=${pageParam}`) \n return await response.json() \n }'
157 case 'getPreviousPageParam':
158 return 'getPreviousPageParam: (firstPage) => firstPage.previousId ?? undefined'
159 case 'getNextPageParam':
160 return 'getNextPageParam: (lastPage) => lastPage.nextId ?? undefined'
161 }
162 }
163 return `
164 import { ${infiniteQueryFunction} } from '@tanstack/react-query'
165β
166 ${infiniteQueryFunction}({
167 ${properties.map(getPropertyCode).join(',\n ')}
168 })
169 `
170}
171β
172const validTestCases = validTestMatrix.map(
173 ({ infiniteQueryFunction, properties }) => ({
174 name: `should pass when order is correct for ${infiniteQueryFunction} with order: ${properties.join(', ')}`,
175 code: getCode({ infiniteQueryFunction, properties }),
176 }),
177)
178β
179const invalidTestCases = invalidTestMatrix.map(
180 ({ infiniteQueryFunction, properties }) => ({
181 name: `incorrect property order is detected for ${infiniteQueryFunction} with invalid order: ${properties.invalid.join(', ')}, valid order: ${properties.valid.join(', ')}`,
182 code: getCode({
183 infiniteQueryFunction: infiniteQueryFunction,
184 properties: properties.invalid,
185 }),
186 errors: [{ messageId: 'invalidOrder' }],
187 output: getCode({
188 infiniteQueryFunction: infiniteQueryFunction,
189 properties: properties.valid,
190 }),
191 }),
192)
193β
194ruleTester.run(name, rule, {
195 valid: validTestCases,
196 invalid: invalidTestCases,
197})
198β
199// regression tests
200β
201const regressionTestCases = {
202 valid: [
203 {
204 name: 'should pass with call expression spread',
205 code: normalizeIndent`
206 import { useInfiniteQuery } from '@tanstack/react-query'
207 const { data, isFetching, isLoading, hasNextPage, fetchNextPage } =
208 useInfiniteQuery({
209 ...communitiesQuery({
210 filters: {
211 ...fieldValues,
212 placementFormats: [],
213 },
214 }),
215 refetchOnMount: false,
216 })`,
217 },
218 ],
219 invalid: [],
220}
221β
222ruleTester.run(name, rule, regressionTestCases)