首页/测试 & QA/javascript-typescript-jest
J

javascript-typescript-jest

by @githubv
4.5(317)

提供使用Jest编写JavaScript/TypeScript测试的最佳实践,包括模拟策略、测试结构和常见模式。

javascripttypescriptjestunit-testingnodejsGitHub
安装方式
npx skills add github/awesome-copilot --skill javascript-typescript-jest
compare_arrows

Before / After 效果对比

1
使用前

编写JavaScript/TypeScript测试时,缺乏统一的Jest最佳实践,导致测试代码质量低、维护困难。测试覆盖率不足,难以保证代码质量。

使用后

遵循Jest最佳实践,测试代码结构清晰、易于维护,模拟策略高效。显著提升了测试效率和代码质量,确保应用稳定性。

SKILL.md

Test Structure

  • Name test files with .test.ts or .test.js suffix
  • 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() or mockReturnValue() to define mock behavior
  • Reset mocks between tests with jest.resetAllMocks() in afterEach

Testing Async Code

  • Always return promises or use async/await syntax in tests
  • Use resolves/rejects matchers 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 userEvent over fireEvent for 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)

用户评价 (0)

发表评价

效果
易用性
文档
兼容性

暂无评价

统计数据

安装量10.6K
评分4.5 / 5.0
版本
更新日期2026年5月21日
对比案例1 组

用户评分

4.5(317)
5
23%
4
51%
3
23%
2
2%
1
0%

为此 Skill 评分

0.0

兼容平台

🔧Claude Code
🔧OpenClaw
🔧OpenCode
🔧Codex
🔧Gemini CLI
🔧GitHub Copilot
🔧Amp
🔧Kimi CLI

时间线

创建2026年3月16日
最后更新2026年5月21日