Skip to content

Commit 64c97b9

Browse files
committed
feat(prefer-user-event-setup): adding new rule
1 parent c945daf commit 64c97b9

File tree

3 files changed

+650
-0
lines changed

3 files changed

+650
-0
lines changed
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
# Suggest using userEvent with setup() instead of direct methods (`testing-library/prefer-user-event-setup`)
2+
3+
<!-- end auto-generated rule header -->
4+
5+
## Rule Details
6+
7+
This rule enforces using methods on instances returned by `userEvent.setup()` instead of calling methods directly on the `userEvent` object. The setup pattern is the [recommended approach](https://testing-library.com/docs/user-event/intro/#writing-tests-with-userevent) in the official user-event documentation.
8+
9+
Using `userEvent.setup()` provides several benefits:
10+
11+
- Ensures proper initialization of the user-event system
12+
- Better reflects real user interactions with proper event sequencing
13+
- Provides consistent timing behavior across different environments
14+
- Allows configuration of delays and other options
15+
16+
### Why Use setup()?
17+
18+
Starting with user-event v14, the library recommends calling `userEvent.setup()` before rendering your component and using the returned instance for all user interactions. This ensures that the event system is properly initialized and that all events are fired in the correct order.
19+
20+
## Examples
21+
22+
Examples of **incorrect** code for this rule:
23+
24+
```js
25+
import userEvent from '@testing-library/user-event';
26+
import { render, screen } from '@testing-library/react';
27+
28+
test('clicking a button', async () => {
29+
render(<MyComponent />);
30+
// ❌ Direct call without setup()
31+
await userEvent.click(screen.getByRole('button'));
32+
});
33+
34+
test('typing in input', async () => {
35+
render(<MyComponent />);
36+
// ❌ Direct call without setup()
37+
await userEvent.type(screen.getByRole('textbox'), 'Hello');
38+
});
39+
40+
test('multiple interactions', async () => {
41+
render(<MyComponent />);
42+
// ❌ Multiple direct calls
43+
await userEvent.type(screen.getByRole('textbox'), 'Hello');
44+
await userEvent.click(screen.getByRole('button'));
45+
});
46+
```
47+
48+
Examples of **correct** code for this rule:
49+
50+
```js
51+
import userEvent from '@testing-library/user-event';
52+
import { render, screen } from '@testing-library/react';
53+
54+
test('clicking a button', async () => {
55+
// ✅ Create user instance with setup()
56+
const user = userEvent.setup();
57+
render(<MyComponent />);
58+
await user.click(screen.getByRole('button'));
59+
});
60+
61+
test('typing in input', async () => {
62+
// ✅ Create user instance with setup()
63+
const user = userEvent.setup();
64+
render(<MyComponent />);
65+
await user.type(screen.getByRole('textbox'), 'Hello');
66+
});
67+
68+
test('multiple interactions', async () => {
69+
// ✅ Use the same user instance for all interactions
70+
const user = userEvent.setup();
71+
render(<MyComponent />);
72+
await user.type(screen.getByRole('textbox'), 'Hello');
73+
await user.click(screen.getByRole('button'));
74+
});
75+
76+
// ✅ Using a setup function pattern
77+
function setup(jsx) {
78+
return {
79+
user: userEvent.setup(),
80+
...render(jsx),
81+
};
82+
}
83+
84+
test('with custom setup function', async () => {
85+
const { user, getByRole } = setup(<MyComponent />);
86+
await user.click(getByRole('button'));
87+
});
88+
```
89+
90+
### Custom Render Functions
91+
92+
A common pattern is to create a custom render function that includes the user-event setup:
93+
94+
```js
95+
import userEvent from '@testing-library/user-event';
96+
import { render } from '@testing-library/react';
97+
98+
function renderWithUser(ui, options) {
99+
return {
100+
user: userEvent.setup(),
101+
...render(ui, options),
102+
};
103+
}
104+
105+
test('using custom render', async () => {
106+
const { user, getByRole } = renderWithUser(<MyComponent />);
107+
await user.click(getByRole('button'));
108+
});
109+
```
110+
111+
## When Not To Use This Rule
112+
113+
If you're using an older version of user-event (< v14) that doesn't support or require the setup pattern, you may want to disable this rule.
114+
115+
## Further Reading
116+
117+
- [user-event documentation - Writing tests with userEvent](https://testing-library.com/docs/user-event/intro/#writing-tests-with-userevent)
118+
- [user-event setup() API](https://testing-library.com/docs/user-event/setup)
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
2+
3+
import { createTestingLibraryRule } from '../create-testing-library-rule';
4+
5+
import type { TSESTree } from '@typescript-eslint/utils';
6+
7+
export const RULE_NAME = 'prefer-user-event-setup';
8+
9+
export type MessageIds = 'preferUserEventSetup';
10+
export type Options = [];
11+
12+
const USER_EVENT_PACKAGE = '@testing-library/user-event';
13+
const USER_EVENT_NAME = 'userEvent';
14+
const SETUP_METHOD_NAME = 'setup';
15+
16+
// All userEvent methods that should use setup()
17+
const USER_EVENT_METHODS = [
18+
'clear',
19+
'click',
20+
'copy',
21+
'cut',
22+
'dblClick',
23+
'deselectOptions',
24+
'hover',
25+
'keyboard',
26+
'pointer',
27+
'paste',
28+
'selectOptions',
29+
'tripleClick',
30+
'type',
31+
'unhover',
32+
'upload',
33+
'tab',
34+
] as const;
35+
36+
export default createTestingLibraryRule<Options, MessageIds>({
37+
name: RULE_NAME,
38+
meta: {
39+
type: 'problem',
40+
docs: {
41+
description:
42+
'Suggest using userEvent with setup() instead of direct methods',
43+
recommendedConfig: {
44+
dom: false,
45+
angular: false,
46+
react: false,
47+
vue: false,
48+
svelte: false,
49+
marko: false,
50+
},
51+
},
52+
messages: {
53+
preferUserEventSetup:
54+
'Prefer using userEvent with setup() instead of direct {{method}}() call. Use: const user = userEvent.setup(); await user.{{method}}(...)',
55+
},
56+
schema: [],
57+
},
58+
defaultOptions: [],
59+
60+
create(context) {
61+
// Track variables assigned from userEvent.setup()
62+
const userEventSetupVars = new Set<string>();
63+
64+
// Track functions that return userEvent.setup() instances
65+
const setupFunctions = new Map<string, Set<string>>();
66+
67+
// Track imported userEvent identifier (could be aliased)
68+
let userEventIdentifier: string | null = null;
69+
70+
function isUserEventSetupCall(node: TSESTree.Node): boolean {
71+
return (
72+
node.type === AST_NODE_TYPES.CallExpression &&
73+
node.callee.type === AST_NODE_TYPES.MemberExpression &&
74+
node.callee.object.type === AST_NODE_TYPES.Identifier &&
75+
node.callee.object.name === userEventIdentifier &&
76+
node.callee.property.type === AST_NODE_TYPES.Identifier &&
77+
node.callee.property.name === SETUP_METHOD_NAME
78+
);
79+
}
80+
81+
function isDirectUserEventMethodCall(
82+
node: TSESTree.MemberExpression
83+
): boolean {
84+
return (
85+
node.object.type === AST_NODE_TYPES.Identifier &&
86+
node.object.name === userEventIdentifier &&
87+
node.property.type === AST_NODE_TYPES.Identifier &&
88+
USER_EVENT_METHODS.includes(
89+
node.property.name as (typeof USER_EVENT_METHODS)[number]
90+
)
91+
);
92+
}
93+
94+
return {
95+
// Track userEvent imports
96+
ImportDeclaration(node: TSESTree.ImportDeclaration) {
97+
if (node.source.value === USER_EVENT_PACKAGE) {
98+
// Default import: import userEvent from '@testing-library/user-event'
99+
const defaultImport = node.specifiers.find(
100+
(spec) => spec.type === AST_NODE_TYPES.ImportDefaultSpecifier
101+
);
102+
if (defaultImport) {
103+
userEventIdentifier = defaultImport.local.name;
104+
}
105+
106+
// Named import: import { userEvent } from '@testing-library/user-event'
107+
const namedImport = node.specifiers.find(
108+
(spec) =>
109+
spec.type === AST_NODE_TYPES.ImportSpecifier &&
110+
spec.imported.type === AST_NODE_TYPES.Identifier &&
111+
spec.imported.name === USER_EVENT_NAME
112+
);
113+
if (
114+
namedImport &&
115+
namedImport.type === AST_NODE_TYPES.ImportSpecifier
116+
) {
117+
userEventIdentifier = namedImport.local.name;
118+
}
119+
}
120+
},
121+
122+
// Track variables assigned from userEvent.setup()
123+
VariableDeclarator(node: TSESTree.VariableDeclarator) {
124+
if (!userEventIdentifier || !node.init) return;
125+
126+
// Direct assignment: const user = userEvent.setup()
127+
if (
128+
isUserEventSetupCall(node.init) &&
129+
node.id.type === AST_NODE_TYPES.Identifier
130+
) {
131+
userEventSetupVars.add(node.id.name);
132+
}
133+
134+
// Destructuring from a setup function
135+
if (
136+
node.id.type === AST_NODE_TYPES.ObjectPattern &&
137+
node.init.type === AST_NODE_TYPES.CallExpression &&
138+
node.init.callee.type === AST_NODE_TYPES.Identifier
139+
) {
140+
const functionName = node.init.callee.name;
141+
const setupProps = setupFunctions.get(functionName);
142+
143+
if (setupProps) {
144+
for (const prop of node.id.properties) {
145+
if (
146+
prop.type === AST_NODE_TYPES.Property &&
147+
prop.key.type === AST_NODE_TYPES.Identifier &&
148+
setupProps.has(prop.key.name) &&
149+
prop.value.type === AST_NODE_TYPES.Identifier
150+
) {
151+
userEventSetupVars.add(prop.value.name);
152+
}
153+
}
154+
}
155+
}
156+
},
157+
158+
// Track functions that return objects with userEvent.setup()
159+
// Note: This simplified implementation only checks direct return statements
160+
// in the function body, not nested functions or complex flows
161+
FunctionDeclaration(node: TSESTree.FunctionDeclaration) {
162+
if (!userEventIdentifier || !node.id) return;
163+
164+
// For simplicity, only check direct return statements in the function body
165+
if (node.body && node.body.type === AST_NODE_TYPES.BlockStatement) {
166+
for (const statement of node.body.body) {
167+
if (statement.type === AST_NODE_TYPES.ReturnStatement) {
168+
const ret = statement;
169+
if (
170+
ret.argument &&
171+
ret.argument.type === AST_NODE_TYPES.ObjectExpression
172+
) {
173+
const props = new Set<string>();
174+
for (const prop of ret.argument.properties) {
175+
if (
176+
prop.type === AST_NODE_TYPES.Property &&
177+
prop.key.type === AST_NODE_TYPES.Identifier &&
178+
prop.value &&
179+
isUserEventSetupCall(prop.value)
180+
) {
181+
props.add(prop.key.name);
182+
}
183+
}
184+
if (props.size > 0) {
185+
setupFunctions.set(node.id.name, props);
186+
}
187+
}
188+
}
189+
}
190+
}
191+
},
192+
193+
// Check for direct userEvent method calls
194+
CallExpression(node: TSESTree.CallExpression) {
195+
if (!userEventIdentifier) return;
196+
197+
if (
198+
node.callee.type === AST_NODE_TYPES.MemberExpression &&
199+
isDirectUserEventMethodCall(node.callee)
200+
) {
201+
const methodName = (node.callee.property as TSESTree.Identifier).name;
202+
203+
// Check if this is called on a setup instance
204+
const isSetupInstance =
205+
node.callee.object.type === AST_NODE_TYPES.Identifier &&
206+
userEventSetupVars.has(node.callee.object.name);
207+
208+
if (!isSetupInstance) {
209+
context.report({
210+
node: node.callee,
211+
messageId: 'preferUserEventSetup',
212+
data: {
213+
method: methodName,
214+
},
215+
});
216+
}
217+
}
218+
},
219+
};
220+
},
221+
});

0 commit comments

Comments
 (0)