| name | testing-jest-unit-test-generation |
| description | null |
Unit Test Generation
Category: testing-jest · Status: 🟢 Active
When to use
Khi viết unit test (Jest + Testing Library) cho function/component/hook.
Steps
- Xác định đơn vị cần test và contract (input → output/side-effect).
- Cấu trúc AAA: Arrange, Act, Assert; mỗi test 1 hành vi.
- Test theo hành vi người dùng (getByRole/Text), không test chi tiết nội bộ.
- Phủ happy path + edge case + lỗi.
- Tên test mô tả hành vi:
it('hiển thị lỗi khi email trống').
Template
it('gọi onSubmit với giá trị đã nhập', async () => {
const onSubmit = jest.fn();
render(<LoginForm onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText('Email'), 'a@b.com');
await userEvent.click(screen.getByRole('button', { name: /đăng nhập/i }));
expect(onSubmit).toHaveBeenCalledWith({ email: 'a@b.com' });
});
Example
Good: query theo role, assert hành vi, tên test rõ.
Avoid: test implementation detail, snapshot bừa, không cleanup.
Checklist