javascript-typescript-jest
bởi github
Các phương pháp kiểm thử Jest tốt nhất cho các dự án JavaScript và TypeScript với mock, xử lý bất đồng bộ và các mẫu React. Tổ chức các bài kiểm tra với tên mô tả trong các khối describe lồng nhau, sử dụng các tệp .test.ts / .test.js đặt cùng với mã nguồn hoặc trong thư mục __tests__. Mock các phụ thuộc bên ngoài bằng jest.mock(), jest.spyOn() và mockImplementation(), đặt lại giữa các bài kiểm tra để ngăn rò rỉ trạng thái. Xử lý mã bất đồng bộ với promise, async/await và các bộ so khớp resolves / rejects; thiết lập...
npx skills add https://github.com/github/awesome-copilot --skill javascript-typescript-jestTest Structure
- Name test files with
.test.tsor.test.jssuffix - Place test files next to the code they test or in a dedicated
__tests__directory - Use descriptive test names that explain the expected behavior
- Use nested describe blocks to organize related tests
- Follow the pattern:
describe('Component/Function/Class', () => { it('should do something', () => {}) })
Effective Mocking
- Mock external dependencies (APIs, databases, etc.) to isolate your tests
- Use
jest.mock()for module-level mocks - Use
jest.spyOn()for specific function mocks - Use
mockImplementation()ormockReturnValue()to define mock behavior - Reset mocks between tests with
jest.resetAllMocks()inafterEach
Testing Async Code
- Always return promises or use async/await syntax in tests
- Use
resolves/rejectsmatchers for promises - Set appropriate timeouts for slow tests with
jest.setTimeout()
Snapshot Testing
- Use snapshot tests for UI components or complex objects that change infrequently
- Keep snapshots small and focused
- Review snapshot changes carefully before committing
Testing React Components
- Use React Testing Library over Enzyme for testing components
- Test user behavior and component accessibility
- Query elements by accessibility roles, labels, or text content
- Use
userEventoverfireEventfor more realistic user interactions
Common Jest Matchers
- Basic:
expect(value).toBe(expected),expect(value).toEqual(expected) - Truthiness:
expect(value).toBeTruthy(),expect(value).toBeFalsy() - Numbers:
expect(value).toBeGreaterThan(3),expect(value).toBeLessThanOrEqual(3) - Strings:
expect(value).toMatch(/pattern/),expect(value).toContain('substring') - Arrays:
expect(array).toContain(item),expect(array).toHaveLength(3) - Objects:
expect(object).toHaveProperty('key', value) - Exceptions:
expect(fn).toThrow(),expect(fn).toThrow(Error) - Mock functions:
expect(mockFn).toHaveBeenCalled(),expect(mockFn).toHaveBeenCalledWith(arg1, arg2)