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