Testingintermediate
Refactor tests to follow AAA pattern and best practices
Test Refactorer
Refactor tests to follow AAA pattern and best practices
Refactor tests to follow best practices and the AAA pattern.
Instructions
-
Read existing tests and identify issues:
- Tests doing too many things (multiple behaviors in one test)
- Missing arrange/act/assert separation
- Shared mutable state between tests
- Tests depending on execution order
- Overly complex setup (signals poor test design)
-
Apply fixes:
Before (bad):
test('user operations', async () => {
const user = await createUser('Alice');
expect(user.id).toBeDefined();
await updateUser(user.id, { name: 'Bob' });
const updated = await getUser(user.id);
expect(updated.name).toBe('Bob');
await deleteUser(user.id);
expect(await getUser(user.id)).toBeNull();
});
After (good):
describe('UserService', () => {
it('should create user with generated id', async () => {
const user = await createUser('Alice');
expect(user.id).toBeDefined();
expect(user.name).toBe('Alice');
});
it('should update user name', async () => {
const user = await createUser('Alice');
await updateUser(user.id, { name: 'Bob' });
expect((await getUser(user.id)).name).toBe('Bob');
});
it('should return null for deleted user', async () => {
const user = await createUser('Alice');
await deleteUser(user.id);
expect(await getUser(user.id)).toBeNull();
});
});
Rules
- Each test is independent — can run alone or in any order
- Use
beforeEachfor shared setup, never shared mutable variables - Test name describes the behavior:
should [expected] when [condition]