@zimezone/z-command 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/README.md +13 -1
  2. package/dist/commands/init.d.ts.map +1 -1
  3. package/dist/commands/init.js +34 -9
  4. package/dist/commands/init.js.map +1 -1
  5. package/package.json +8 -3
  6. package/templates.zip +0 -0
  7. package/templates/agents/accessibility-expert.agent.md +0 -56
  8. package/templates/agents/ai-engineer.agent.md +0 -61
  9. package/templates/agents/angular-architect.agent.md +0 -49
  10. package/templates/agents/api-designer.agent.md +0 -40
  11. package/templates/agents/api-documenter.agent.md +0 -161
  12. package/templates/agents/architect-review.agent.md +0 -146
  13. package/templates/agents/arm-cortex-expert.agent.md +0 -288
  14. package/templates/agents/azure-infra-engineer.agent.md +0 -57
  15. package/templates/agents/backend-architect.agent.md +0 -309
  16. package/templates/agents/backend-developer.agent.md +0 -61
  17. package/templates/agents/backend-security-coder.agent.md +0 -152
  18. package/templates/agents/bash-pro.agent.md +0 -285
  19. package/templates/agents/blockchain-developer.agent.md +0 -57
  20. package/templates/agents/build-engineer.agent.md +0 -56
  21. package/templates/agents/business-analyst.agent.md +0 -47
  22. package/templates/agents/c-pro.agent.md +0 -35
  23. package/templates/agents/c4-code.agent.md +0 -320
  24. package/templates/agents/c4-component.agent.md +0 -227
  25. package/templates/agents/c4-container.agent.md +0 -248
  26. package/templates/agents/c4-context.agent.md +0 -235
  27. package/templates/agents/cli-developer.agent.md +0 -57
  28. package/templates/agents/cloud-architect.agent.md +0 -56
  29. package/templates/agents/code-architect.agent.md +0 -63
  30. package/templates/agents/code-reviewer.agent.md +0 -49
  31. package/templates/agents/competitive-analyst.agent.md +0 -48
  32. package/templates/agents/conductor-validator.agent.md +0 -245
  33. package/templates/agents/context-manager.agent.md +0 -55
  34. package/templates/agents/cpp-pro.agent.md +0 -59
  35. package/templates/agents/csharp-developer.agent.md +0 -57
  36. package/templates/agents/csharp-pro.agent.md +0 -38
  37. package/templates/agents/customer-support.agent.md +0 -148
  38. package/templates/agents/data-engineer.agent.md +0 -55
  39. package/templates/agents/data-researcher.agent.md +0 -55
  40. package/templates/agents/data-scientist.agent.md +0 -56
  41. package/templates/agents/database-admin.agent.md +0 -142
  42. package/templates/agents/database-administrator.agent.md +0 -50
  43. package/templates/agents/database-architect.agent.md +0 -238
  44. package/templates/agents/database-optimizer.agent.md +0 -144
  45. package/templates/agents/debugger.agent.md +0 -30
  46. package/templates/agents/deployment-engineer.agent.md +0 -0
  47. package/templates/agents/devops-engineer.agent.md +0 -59
  48. package/templates/agents/devops-troubleshooter.agent.md +0 -138
  49. package/templates/agents/django-developer.agent.md +0 -50
  50. package/templates/agents/django-pro.agent.md +0 -159
  51. package/templates/agents/docs-architect.agent.md +0 -77
  52. package/templates/agents/documentation-engineer.agent.md +0 -57
  53. package/templates/agents/dotnet-architect.agent.md +0 -175
  54. package/templates/agents/dx-optimizer.agent.md +0 -63
  55. package/templates/agents/electron-pro.agent.md +0 -56
  56. package/templates/agents/elixir-pro.agent.md +0 -38
  57. package/templates/agents/embedded-systems.agent.md +0 -55
  58. package/templates/agents/error-detective.agent.md +0 -32
  59. package/templates/agents/event-sourcing-architect.agent.md +0 -42
  60. package/templates/agents/fastapi-pro.agent.md +0 -171
  61. package/templates/agents/fintech-engineer.agent.md +0 -57
  62. package/templates/agents/firmware-analyst.agent.md +0 -330
  63. package/templates/agents/flutter-expert.agent.md +0 -50
  64. package/templates/agents/frontend-developer.agent.md +0 -59
  65. package/templates/agents/frontend-security-coder.agent.md +0 -149
  66. package/templates/agents/fullstack-developer.agent.md +0 -46
  67. package/templates/agents/git-workflow-manager.agent.md +0 -57
  68. package/templates/agents/golang-pro.agent.md +0 -50
  69. package/templates/agents/graphql-architect.agent.md +0 -48
  70. package/templates/agents/haskell-pro.agent.md +0 -37
  71. package/templates/agents/hr-pro.agent.md +0 -105
  72. package/templates/agents/incident-responder.agent.md +0 -190
  73. package/templates/agents/ios-developer.agent.md +0 -198
  74. package/templates/agents/iot-engineer.agent.md +0 -56
  75. package/templates/agents/java-architect.agent.md +0 -48
  76. package/templates/agents/java-pro.agent.md +0 -156
  77. package/templates/agents/javascript-pro.agent.md +0 -35
  78. package/templates/agents/julia-pro.agent.md +0 -187
  79. package/templates/agents/kotlin-specialist.agent.md +0 -50
  80. package/templates/agents/laravel-specialist.agent.md +0 -50
  81. package/templates/agents/legacy-modernizer.agent.md +0 -56
  82. package/templates/agents/legal-advisor.agent.md +0 -49
  83. package/templates/agents/llm-architect.agent.md +0 -58
  84. package/templates/agents/malware-analyst.agent.md +0 -272
  85. package/templates/agents/mcp-developer.agent.md +0 -54
  86. package/templates/agents/mermaid-expert.agent.md +0 -39
  87. package/templates/agents/microservices-architect.agent.md +0 -47
  88. package/templates/agents/minecraft-bukkit-pro.agent.md +0 -104
  89. package/templates/agents/ml-engineer.agent.md +0 -56
  90. package/templates/agents/mlops-engineer.agent.md +0 -56
  91. package/templates/agents/mobile-developer.agent.md +0 -45
  92. package/templates/agents/mobile-security-coder.agent.md +0 -163
  93. package/templates/agents/monorepo-architect.agent.md +0 -44
  94. package/templates/agents/multi-agent-coordinator.agent.md +0 -55
  95. package/templates/agents/network-engineer.agent.md +0 -57
  96. package/templates/agents/nextjs-developer.agent.md +0 -48
  97. package/templates/agents/nlp-engineer.agent.md +0 -58
  98. package/templates/agents/observability-engineer.agent.md +0 -228
  99. package/templates/agents/payment-integration.agent.md +0 -56
  100. package/templates/agents/performance-engineer.agent.md +0 -167
  101. package/templates/agents/performance-optimizer.agent.md +0 -57
  102. package/templates/agents/php-pro.agent.md +0 -43
  103. package/templates/agents/platform-engineer.agent.md +0 -57
  104. package/templates/agents/posix-shell-pro.agent.md +0 -284
  105. package/templates/agents/postgres-pro.agent.md +0 -58
  106. package/templates/agents/product-manager.agent.md +0 -55
  107. package/templates/agents/project-manager.agent.md +0 -57
  108. package/templates/agents/prompt-engineer.agent.md +0 -58
  109. package/templates/agents/python-pro.agent.md +0 -48
  110. package/templates/agents/quant-analyst.agent.md +0 -32
  111. package/templates/agents/rails-expert.agent.md +0 -50
  112. package/templates/agents/react-specialist.agent.md +0 -49
  113. package/templates/agents/refactoring-specialist.agent.md +0 -56
  114. package/templates/agents/reference-builder.agent.md +0 -167
  115. package/templates/agents/research-analyst.agent.md +0 -63
  116. package/templates/agents/reverse-engineer.agent.md +0 -202
  117. package/templates/agents/risk-manager.agent.md +0 -41
  118. package/templates/agents/ruby-pro.agent.md +0 -35
  119. package/templates/agents/rust-pro.agent.md +0 -156
  120. package/templates/agents/sales-automator.agent.md +0 -35
  121. package/templates/agents/scala-pro.agent.md +0 -60
  122. package/templates/agents/scrum-master.agent.md +0 -54
  123. package/templates/agents/search-specialist.agent.md +0 -59
  124. package/templates/agents/security-analyst.agent.md +0 -57
  125. package/templates/agents/security-auditor.agent.md +0 -138
  126. package/templates/agents/security-engineer.agent.md +0 -57
  127. package/templates/agents/seo-authority-builder.agent.md +0 -116
  128. package/templates/agents/seo-cannibalization-detector.agent.md +0 -103
  129. package/templates/agents/seo-content-auditor.agent.md +0 -63
  130. package/templates/agents/seo-content-planner.agent.md +0 -88
  131. package/templates/agents/seo-content-refresher.agent.md +0 -98
  132. package/templates/agents/seo-content-writer.agent.md +0 -76
  133. package/templates/agents/seo-keyword-strategist.agent.md +0 -75
  134. package/templates/agents/seo-meta-optimizer.agent.md +0 -72
  135. package/templates/agents/seo-snippet-hunter.agent.md +0 -94
  136. package/templates/agents/seo-specialist.agent.md +0 -57
  137. package/templates/agents/seo-structure-architect.agent.md +0 -88
  138. package/templates/agents/service-mesh-expert.agent.md +0 -41
  139. package/templates/agents/sql-pro.agent.md +0 -146
  140. package/templates/agents/sre-engineer.agent.md +0 -58
  141. package/templates/agents/swift-expert.agent.md +0 -49
  142. package/templates/agents/task-distributor.agent.md +0 -47
  143. package/templates/agents/tdd-orchestrator.agent.md +0 -183
  144. package/templates/agents/technical-writer.agent.md +0 -48
  145. package/templates/agents/temporal-python-pro.agent.md +0 -349
  146. package/templates/agents/terraform-engineer.agent.md +0 -57
  147. package/templates/agents/terraform-specialist.agent.md +0 -137
  148. package/templates/agents/test-automator.agent.md +0 -203
  149. package/templates/agents/test-engineer.agent.md +0 -55
  150. package/templates/agents/threat-modeling-expert.agent.md +0 -44
  151. package/templates/agents/trend-analyst.agent.md +0 -47
  152. package/templates/agents/tutorial-engineer.agent.md +0 -118
  153. package/templates/agents/typescript-pro.agent.md +0 -48
  154. package/templates/agents/ui-designer.agent.md +0 -48
  155. package/templates/agents/ui-ux-designer.agent.md +0 -188
  156. package/templates/agents/ui-visual-validator.agent.md +0 -192
  157. package/templates/agents/ux-researcher.agent.md +0 -48
  158. package/templates/agents/vector-database-engineer.agent.md +0 -43
  159. package/templates/agents/vue-expert.agent.md +0 -48
  160. package/templates/agents/websocket-engineer.agent.md +0 -49
  161. package/templates/agents/workflow-orchestrator.agent.md +0 -48
  162. package/templates/skills/angular-migration/SKILL.md +0 -410
  163. package/templates/skills/api-design-principles/SKILL.md +0 -528
  164. package/templates/skills/api-design-principles/assets/api-design-checklist.md +0 -155
  165. package/templates/skills/api-design-principles/assets/rest-api-template.py +0 -182
  166. package/templates/skills/api-design-principles/references/graphql-schema-design.md +0 -583
  167. package/templates/skills/api-design-principles/references/rest-best-practices.md +0 -408
  168. package/templates/skills/architecture-decision-records/SKILL.md +0 -428
  169. package/templates/skills/architecture-patterns/SKILL.md +0 -494
  170. package/templates/skills/async-python-patterns/SKILL.md +0 -694
  171. package/templates/skills/auth-implementation-patterns/SKILL.md +0 -634
  172. package/templates/skills/changelog-automation/SKILL.md +0 -552
  173. package/templates/skills/code-review/SKILL.md +0 -62
  174. package/templates/skills/code-review-excellence/SKILL.md +0 -520
  175. package/templates/skills/competitive-landscape/SKILL.md +0 -479
  176. package/templates/skills/context-driven-development/SKILL.md +0 -385
  177. package/templates/skills/cost-optimization/SKILL.md +0 -274
  178. package/templates/skills/cqrs-implementation/SKILL.md +0 -554
  179. package/templates/skills/data-quality-frameworks/SKILL.md +0 -587
  180. package/templates/skills/data-storytelling/SKILL.md +0 -453
  181. package/templates/skills/database-migration/SKILL.md +0 -424
  182. package/templates/skills/dbt-transformation-patterns/SKILL.md +0 -561
  183. package/templates/skills/debugging-strategies/SKILL.md +0 -527
  184. package/templates/skills/defi-protocol-templates/SKILL.md +0 -454
  185. package/templates/skills/dependency-upgrade/SKILL.md +0 -409
  186. package/templates/skills/deployment-pipeline-design/SKILL.md +0 -359
  187. package/templates/skills/distributed-tracing/SKILL.md +0 -438
  188. package/templates/skills/dotnet-backend-patterns/SKILL.md +0 -815
  189. package/templates/skills/dotnet-backend-patterns/assets/repository-template.cs +0 -523
  190. package/templates/skills/dotnet-backend-patterns/assets/service-template.cs +0 -336
  191. package/templates/skills/dotnet-backend-patterns/references/dapper-patterns.md +0 -544
  192. package/templates/skills/dotnet-backend-patterns/references/ef-core-best-practices.md +0 -355
  193. package/templates/skills/e2e-testing-patterns/SKILL.md +0 -547
  194. package/templates/skills/employment-contract-templates/SKILL.md +0 -507
  195. package/templates/skills/error-handling-patterns/SKILL.md +0 -636
  196. package/templates/skills/event-store-design/SKILL.md +0 -437
  197. package/templates/skills/fastapi-templates/SKILL.md +0 -567
  198. package/templates/skills/git-advanced-workflows/SKILL.md +0 -400
  199. package/templates/skills/github-actions-templates/SKILL.md +0 -333
  200. package/templates/skills/go-concurrency-patterns/SKILL.md +0 -655
  201. package/templates/skills/grafana-dashboards/SKILL.md +0 -369
  202. package/templates/skills/helm-chart-scaffolding/SKILL.md +0 -544
  203. package/templates/skills/helm-chart-scaffolding/assets/Chart.yaml.template +0 -42
  204. package/templates/skills/helm-chart-scaffolding/assets/values.yaml.template +0 -185
  205. package/templates/skills/helm-chart-scaffolding/references/chart-structure.md +0 -500
  206. package/templates/skills/helm-chart-scaffolding/scripts/validate-chart.sh +0 -244
  207. package/templates/skills/javascript-testing-patterns/SKILL.md +0 -1025
  208. package/templates/skills/langchain-architecture/SKILL.md +0 -338
  209. package/templates/skills/llm-evaluation/SKILL.md +0 -471
  210. package/templates/skills/microservices-patterns/SKILL.md +0 -595
  211. package/templates/skills/modern-javascript-patterns/SKILL.md +0 -911
  212. package/templates/skills/monorepo-management/SKILL.md +0 -622
  213. package/templates/skills/nextjs-app-router-patterns/SKILL.md +0 -544
  214. package/templates/skills/nodejs-backend-patterns/SKILL.md +0 -1020
  215. package/templates/skills/nx-workspace-patterns/SKILL.md +0 -452
  216. package/templates/skills/openapi-spec-generation/SKILL.md +0 -1028
  217. package/templates/skills/paypal-integration/SKILL.md +0 -467
  218. package/templates/skills/pci-compliance/SKILL.md +0 -466
  219. package/templates/skills/postgresql/SKILL.md +0 -204
  220. package/templates/skills/projection-patterns/SKILL.md +0 -490
  221. package/templates/skills/prometheus-configuration/SKILL.md +0 -392
  222. package/templates/skills/prompt-engineering-patterns/SKILL.md +0 -201
  223. package/templates/skills/prompt-engineering-patterns/assets/few-shot-examples.json +0 -106
  224. package/templates/skills/prompt-engineering-patterns/assets/prompt-template-library.md +0 -246
  225. package/templates/skills/prompt-engineering-patterns/references/chain-of-thought.md +0 -399
  226. package/templates/skills/prompt-engineering-patterns/references/few-shot-learning.md +0 -369
  227. package/templates/skills/prompt-engineering-patterns/references/prompt-optimization.md +0 -414
  228. package/templates/skills/prompt-engineering-patterns/references/prompt-templates.md +0 -470
  229. package/templates/skills/prompt-engineering-patterns/references/system-prompts.md +0 -189
  230. package/templates/skills/prompt-engineering-patterns/scripts/optimize-prompt.py +0 -279
  231. package/templates/skills/python-packaging/SKILL.md +0 -870
  232. package/templates/skills/python-performance-optimization/SKILL.md +0 -869
  233. package/templates/skills/python-testing-patterns/SKILL.md +0 -907
  234. package/templates/skills/rag-implementation/SKILL.md +0 -403
  235. package/templates/skills/react-modernization/SKILL.md +0 -513
  236. package/templates/skills/react-native-architecture/SKILL.md +0 -671
  237. package/templates/skills/react-state-management/SKILL.md +0 -429
  238. package/templates/skills/risk-metrics-calculation/SKILL.md +0 -555
  239. package/templates/skills/rust-async-patterns/SKILL.md +0 -517
  240. package/templates/skills/secrets-management/SKILL.md +0 -346
  241. package/templates/skills/security-requirement-extraction/SKILL.md +0 -677
  242. package/templates/skills/security-review/SKILL.md +0 -78
  243. package/templates/skills/shellcheck-configuration/SKILL.md +0 -454
  244. package/templates/skills/similarity-search-patterns/SKILL.md +0 -558
  245. package/templates/skills/slo-implementation/SKILL.md +0 -329
  246. package/templates/skills/sql-optimization-patterns/SKILL.md +0 -493
  247. package/templates/skills/stripe-integration/SKILL.md +0 -442
  248. package/templates/skills/systematic-debugging/SKILL.md +0 -57
  249. package/templates/skills/tailwind-design-system/SKILL.md +0 -666
  250. package/templates/skills/temporal-python-testing/SKILL.md +0 -158
  251. package/templates/skills/temporal-python-testing/resources/integration-testing.md +0 -455
  252. package/templates/skills/temporal-python-testing/resources/local-setup.md +0 -553
  253. package/templates/skills/temporal-python-testing/resources/replay-testing.md +0 -462
  254. package/templates/skills/temporal-python-testing/resources/unit-testing.md +0 -328
  255. package/templates/skills/terraform-module-library/SKILL.md +0 -249
  256. package/templates/skills/terraform-module-library/references/aws-modules.md +0 -63
  257. package/templates/skills/test-driven-development/SKILL.md +0 -46
  258. package/templates/skills/threat-mitigation-mapping/SKILL.md +0 -745
  259. package/templates/skills/track-management/SKILL.md +0 -593
  260. package/templates/skills/typescript-advanced-types/SKILL.md +0 -717
  261. package/templates/skills/ui-ux-pro-max/SKILL.md +0 -352
  262. package/templates/skills/ui-ux-pro-max/data/charts.csv +0 -26
  263. package/templates/skills/ui-ux-pro-max/data/colors.csv +0 -97
  264. package/templates/skills/ui-ux-pro-max/data/icons.csv +0 -101
  265. package/templates/skills/ui-ux-pro-max/data/landing.csv +0 -31
  266. package/templates/skills/ui-ux-pro-max/data/products.csv +0 -97
  267. package/templates/skills/ui-ux-pro-max/data/prompts.csv +0 -24
  268. package/templates/skills/ui-ux-pro-max/data/react-performance.csv +0 -45
  269. package/templates/skills/ui-ux-pro-max/data/styles.csv +0 -59
  270. package/templates/skills/ui-ux-pro-max/data/typography.csv +0 -58
  271. package/templates/skills/ui-ux-pro-max/data/ui-reasoning.csv +0 -101
  272. package/templates/skills/ui-ux-pro-max/data/ux-guidelines.csv +0 -100
  273. package/templates/skills/ui-ux-pro-max/data/web-interface.csv +0 -31
  274. package/templates/skills/ui-ux-pro-max/scripts/core.py +0 -258
  275. package/templates/skills/ui-ux-pro-max/scripts/design_system.py +0 -547
  276. package/templates/skills/ui-ux-pro-max/scripts/search.py +0 -76
  277. package/templates/skills/uv-package-manager/SKILL.md +0 -831
  278. package/templates/skills/vector-index-tuning/SKILL.md +0 -521
  279. package/templates/skills/wcag-audit-patterns/SKILL.md +0 -555
  280. package/templates/skills/workflow-orchestration-patterns/SKILL.md +0 -316
  281. package/templates/skills/workflow-patterns/SKILL.md +0 -623
  282. package/templates/skills/writing-plans/SKILL.md +0 -64
@@ -1,1025 +0,0 @@
1
- ---
2
- name: javascript-testing-patterns
3
- description: Implement comprehensive testing strategies using Jest, Vitest, and Testing Library for unit tests, integration tests, and end-to-end testing with mocking, fixtures, and test-driven development. Use when writing JavaScript/TypeScript tests, setting up test infrastructure, or implementing TDD/BDD workflows.
4
- ---
5
-
6
- # JavaScript Testing Patterns
7
-
8
- Comprehensive guide for implementing robust testing strategies in JavaScript/TypeScript applications using modern testing frameworks and best practices.
9
-
10
- ## When to Use This Skill
11
-
12
- - Setting up test infrastructure for new projects
13
- - Writing unit tests for functions and classes
14
- - Creating integration tests for APIs and services
15
- - Implementing end-to-end tests for user flows
16
- - Mocking external dependencies and APIs
17
- - Testing React, Vue, or other frontend components
18
- - Implementing test-driven development (TDD)
19
- - Setting up continuous testing in CI/CD pipelines
20
-
21
- ## Testing Frameworks
22
-
23
- ### Jest - Full-Featured Testing Framework
24
-
25
- **Setup:**
26
- ```typescript
27
- // jest.config.ts
28
- import type { Config } from 'jest';
29
-
30
- const config: Config = {
31
- preset: 'ts-jest',
32
- testEnvironment: 'node',
33
- roots: ['<rootDir>/src'],
34
- testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
35
- collectCoverageFrom: [
36
- 'src/**/*.ts',
37
- '!src/**/*.d.ts',
38
- '!src/**/*.interface.ts',
39
- ],
40
- coverageThreshold: {
41
- global: {
42
- branches: 80,
43
- functions: 80,
44
- lines: 80,
45
- statements: 80,
46
- },
47
- },
48
- setupFilesAfterEnv: ['<rootDir>/src/test/setup.ts'],
49
- };
50
-
51
- export default config;
52
- ```
53
-
54
- ### Vitest - Fast, Vite-Native Testing
55
-
56
- **Setup:**
57
- ```typescript
58
- // vitest.config.ts
59
- import { defineConfig } from 'vitest/config';
60
-
61
- export default defineConfig({
62
- test: {
63
- globals: true,
64
- environment: 'node',
65
- coverage: {
66
- provider: 'v8',
67
- reporter: ['text', 'json', 'html'],
68
- exclude: ['**/*.d.ts', '**/*.config.ts', '**/dist/**'],
69
- },
70
- setupFiles: ['./src/test/setup.ts'],
71
- },
72
- });
73
- ```
74
-
75
- ## Unit Testing Patterns
76
-
77
- ### Pattern 1: Testing Pure Functions
78
-
79
- ```typescript
80
- // utils/calculator.ts
81
- export function add(a: number, b: number): number {
82
- return a + b;
83
- }
84
-
85
- export function divide(a: number, b: number): number {
86
- if (b === 0) {
87
- throw new Error('Division by zero');
88
- }
89
- return a / b;
90
- }
91
-
92
- // utils/calculator.test.ts
93
- import { describe, it, expect } from 'vitest';
94
- import { add, divide } from './calculator';
95
-
96
- describe('Calculator', () => {
97
- describe('add', () => {
98
- it('should add two positive numbers', () => {
99
- expect(add(2, 3)).toBe(5);
100
- });
101
-
102
- it('should add negative numbers', () => {
103
- expect(add(-2, -3)).toBe(-5);
104
- });
105
-
106
- it('should handle zero', () => {
107
- expect(add(0, 5)).toBe(5);
108
- expect(add(5, 0)).toBe(5);
109
- });
110
- });
111
-
112
- describe('divide', () => {
113
- it('should divide two numbers', () => {
114
- expect(divide(10, 2)).toBe(5);
115
- });
116
-
117
- it('should handle decimal results', () => {
118
- expect(divide(5, 2)).toBe(2.5);
119
- });
120
-
121
- it('should throw error when dividing by zero', () => {
122
- expect(() => divide(10, 0)).toThrow('Division by zero');
123
- });
124
- });
125
- });
126
- ```
127
-
128
- ### Pattern 2: Testing Classes
129
-
130
- ```typescript
131
- // services/user.service.ts
132
- export class UserService {
133
- private users: Map<string, User> = new Map();
134
-
135
- create(user: User): User {
136
- if (this.users.has(user.id)) {
137
- throw new Error('User already exists');
138
- }
139
- this.users.set(user.id, user);
140
- return user;
141
- }
142
-
143
- findById(id: string): User | undefined {
144
- return this.users.get(id);
145
- }
146
-
147
- update(id: string, updates: Partial<User>): User {
148
- const user = this.users.get(id);
149
- if (!user) {
150
- throw new Error('User not found');
151
- }
152
- const updated = { ...user, ...updates };
153
- this.users.set(id, updated);
154
- return updated;
155
- }
156
-
157
- delete(id: string): boolean {
158
- return this.users.delete(id);
159
- }
160
- }
161
-
162
- // services/user.service.test.ts
163
- import { describe, it, expect, beforeEach } from 'vitest';
164
- import { UserService } from './user.service';
165
-
166
- describe('UserService', () => {
167
- let service: UserService;
168
-
169
- beforeEach(() => {
170
- service = new UserService();
171
- });
172
-
173
- describe('create', () => {
174
- it('should create a new user', () => {
175
- const user = { id: '1', name: 'John', email: 'john@example.com' };
176
- const created = service.create(user);
177
-
178
- expect(created).toEqual(user);
179
- expect(service.findById('1')).toEqual(user);
180
- });
181
-
182
- it('should throw error if user already exists', () => {
183
- const user = { id: '1', name: 'John', email: 'john@example.com' };
184
- service.create(user);
185
-
186
- expect(() => service.create(user)).toThrow('User already exists');
187
- });
188
- });
189
-
190
- describe('update', () => {
191
- it('should update existing user', () => {
192
- const user = { id: '1', name: 'John', email: 'john@example.com' };
193
- service.create(user);
194
-
195
- const updated = service.update('1', { name: 'Jane' });
196
-
197
- expect(updated.name).toBe('Jane');
198
- expect(updated.email).toBe('john@example.com');
199
- });
200
-
201
- it('should throw error if user not found', () => {
202
- expect(() => service.update('999', { name: 'Jane' }))
203
- .toThrow('User not found');
204
- });
205
- });
206
- });
207
- ```
208
-
209
- ### Pattern 3: Testing Async Functions
210
-
211
- ```typescript
212
- // services/api.service.ts
213
- export class ApiService {
214
- async fetchUser(id: string): Promise<User> {
215
- const response = await fetch(`https://api.example.com/users/${id}`);
216
- if (!response.ok) {
217
- throw new Error('User not found');
218
- }
219
- return response.json();
220
- }
221
-
222
- async createUser(user: CreateUserDTO): Promise<User> {
223
- const response = await fetch('https://api.example.com/users', {
224
- method: 'POST',
225
- headers: { 'Content-Type': 'application/json' },
226
- body: JSON.stringify(user),
227
- });
228
- return response.json();
229
- }
230
- }
231
-
232
- // services/api.service.test.ts
233
- import { describe, it, expect, vi, beforeEach } from 'vitest';
234
- import { ApiService } from './api.service';
235
-
236
- // Mock fetch globally
237
- global.fetch = vi.fn();
238
-
239
- describe('ApiService', () => {
240
- let service: ApiService;
241
-
242
- beforeEach(() => {
243
- service = new ApiService();
244
- vi.clearAllMocks();
245
- });
246
-
247
- describe('fetchUser', () => {
248
- it('should fetch user successfully', async () => {
249
- const mockUser = { id: '1', name: 'John', email: 'john@example.com' };
250
-
251
- (fetch as any).mockResolvedValueOnce({
252
- ok: true,
253
- json: async () => mockUser,
254
- });
255
-
256
- const user = await service.fetchUser('1');
257
-
258
- expect(user).toEqual(mockUser);
259
- expect(fetch).toHaveBeenCalledWith('https://api.example.com/users/1');
260
- });
261
-
262
- it('should throw error if user not found', async () => {
263
- (fetch as any).mockResolvedValueOnce({
264
- ok: false,
265
- });
266
-
267
- await expect(service.fetchUser('999')).rejects.toThrow('User not found');
268
- });
269
- });
270
-
271
- describe('createUser', () => {
272
- it('should create user successfully', async () => {
273
- const newUser = { name: 'John', email: 'john@example.com' };
274
- const createdUser = { id: '1', ...newUser };
275
-
276
- (fetch as any).mockResolvedValueOnce({
277
- ok: true,
278
- json: async () => createdUser,
279
- });
280
-
281
- const user = await service.createUser(newUser);
282
-
283
- expect(user).toEqual(createdUser);
284
- expect(fetch).toHaveBeenCalledWith(
285
- 'https://api.example.com/users',
286
- expect.objectContaining({
287
- method: 'POST',
288
- body: JSON.stringify(newUser),
289
- })
290
- );
291
- });
292
- });
293
- });
294
- ```
295
-
296
- ## Mocking Patterns
297
-
298
- ### Pattern 1: Mocking Modules
299
-
300
- ```typescript
301
- // services/email.service.ts
302
- import nodemailer from 'nodemailer';
303
-
304
- export class EmailService {
305
- private transporter = nodemailer.createTransport({
306
- host: process.env.SMTP_HOST,
307
- port: 587,
308
- auth: {
309
- user: process.env.SMTP_USER,
310
- pass: process.env.SMTP_PASS,
311
- },
312
- });
313
-
314
- async sendEmail(to: string, subject: string, html: string) {
315
- await this.transporter.sendMail({
316
- from: process.env.EMAIL_FROM,
317
- to,
318
- subject,
319
- html,
320
- });
321
- }
322
- }
323
-
324
- // services/email.service.test.ts
325
- import { describe, it, expect, vi, beforeEach } from 'vitest';
326
- import { EmailService } from './email.service';
327
-
328
- vi.mock('nodemailer', () => ({
329
- default: {
330
- createTransport: vi.fn(() => ({
331
- sendMail: vi.fn().mockResolvedValue({ messageId: '123' }),
332
- })),
333
- },
334
- }));
335
-
336
- describe('EmailService', () => {
337
- let service: EmailService;
338
-
339
- beforeEach(() => {
340
- service = new EmailService();
341
- });
342
-
343
- it('should send email successfully', async () => {
344
- await service.sendEmail(
345
- 'test@example.com',
346
- 'Test Subject',
347
- '<p>Test Body</p>'
348
- );
349
-
350
- expect(service['transporter'].sendMail).toHaveBeenCalledWith(
351
- expect.objectContaining({
352
- to: 'test@example.com',
353
- subject: 'Test Subject',
354
- })
355
- );
356
- });
357
- });
358
- ```
359
-
360
- ### Pattern 2: Dependency Injection for Testing
361
-
362
- ```typescript
363
- // services/user.service.ts
364
- export interface IUserRepository {
365
- findById(id: string): Promise<User | null>;
366
- create(user: User): Promise<User>;
367
- }
368
-
369
- export class UserService {
370
- constructor(private userRepository: IUserRepository) {}
371
-
372
- async getUser(id: string): Promise<User> {
373
- const user = await this.userRepository.findById(id);
374
- if (!user) {
375
- throw new Error('User not found');
376
- }
377
- return user;
378
- }
379
-
380
- async createUser(userData: CreateUserDTO): Promise<User> {
381
- // Business logic here
382
- const user = { id: generateId(), ...userData };
383
- return this.userRepository.create(user);
384
- }
385
- }
386
-
387
- // services/user.service.test.ts
388
- import { describe, it, expect, vi, beforeEach } from 'vitest';
389
- import { UserService, IUserRepository } from './user.service';
390
-
391
- describe('UserService', () => {
392
- let service: UserService;
393
- let mockRepository: IUserRepository;
394
-
395
- beforeEach(() => {
396
- mockRepository = {
397
- findById: vi.fn(),
398
- create: vi.fn(),
399
- };
400
- service = new UserService(mockRepository);
401
- });
402
-
403
- describe('getUser', () => {
404
- it('should return user if found', async () => {
405
- const mockUser = { id: '1', name: 'John', email: 'john@example.com' };
406
- vi.mocked(mockRepository.findById).mockResolvedValue(mockUser);
407
-
408
- const user = await service.getUser('1');
409
-
410
- expect(user).toEqual(mockUser);
411
- expect(mockRepository.findById).toHaveBeenCalledWith('1');
412
- });
413
-
414
- it('should throw error if user not found', async () => {
415
- vi.mocked(mockRepository.findById).mockResolvedValue(null);
416
-
417
- await expect(service.getUser('999')).rejects.toThrow('User not found');
418
- });
419
- });
420
-
421
- describe('createUser', () => {
422
- it('should create user successfully', async () => {
423
- const userData = { name: 'John', email: 'john@example.com' };
424
- const createdUser = { id: '1', ...userData };
425
-
426
- vi.mocked(mockRepository.create).mockResolvedValue(createdUser);
427
-
428
- const user = await service.createUser(userData);
429
-
430
- expect(user).toEqual(createdUser);
431
- expect(mockRepository.create).toHaveBeenCalled();
432
- });
433
- });
434
- });
435
- ```
436
-
437
- ### Pattern 3: Spying on Functions
438
-
439
- ```typescript
440
- // utils/logger.ts
441
- export const logger = {
442
- info: (message: string) => console.log(`INFO: ${message}`),
443
- error: (message: string) => console.error(`ERROR: ${message}`),
444
- };
445
-
446
- // services/order.service.ts
447
- import { logger } from '../utils/logger';
448
-
449
- export class OrderService {
450
- async processOrder(orderId: string): Promise<void> {
451
- logger.info(`Processing order ${orderId}`);
452
- // Process order logic
453
- logger.info(`Order ${orderId} processed successfully`);
454
- }
455
- }
456
-
457
- // services/order.service.test.ts
458
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
459
- import { OrderService } from './order.service';
460
- import { logger } from '../utils/logger';
461
-
462
- describe('OrderService', () => {
463
- let service: OrderService;
464
- let loggerSpy: any;
465
-
466
- beforeEach(() => {
467
- service = new OrderService();
468
- loggerSpy = vi.spyOn(logger, 'info');
469
- });
470
-
471
- afterEach(() => {
472
- loggerSpy.mockRestore();
473
- });
474
-
475
- it('should log order processing', async () => {
476
- await service.processOrder('123');
477
-
478
- expect(loggerSpy).toHaveBeenCalledWith('Processing order 123');
479
- expect(loggerSpy).toHaveBeenCalledWith('Order 123 processed successfully');
480
- expect(loggerSpy).toHaveBeenCalledTimes(2);
481
- });
482
- });
483
- ```
484
-
485
- ## Integration Testing
486
-
487
- ### Pattern 1: API Integration Tests
488
-
489
- ```typescript
490
- // tests/integration/user.api.test.ts
491
- import request from 'supertest';
492
- import { app } from '../../src/app';
493
- import { pool } from '../../src/config/database';
494
-
495
- describe('User API Integration Tests', () => {
496
- beforeAll(async () => {
497
- // Setup test database
498
- await pool.query('CREATE TABLE IF NOT EXISTS users (...)');
499
- });
500
-
501
- afterAll(async () => {
502
- // Cleanup
503
- await pool.query('DROP TABLE IF EXISTS users');
504
- await pool.end();
505
- });
506
-
507
- beforeEach(async () => {
508
- // Clear data before each test
509
- await pool.query('TRUNCATE TABLE users CASCADE');
510
- });
511
-
512
- describe('POST /api/users', () => {
513
- it('should create a new user', async () => {
514
- const userData = {
515
- name: 'John Doe',
516
- email: 'john@example.com',
517
- password: 'password123',
518
- };
519
-
520
- const response = await request(app)
521
- .post('/api/users')
522
- .send(userData)
523
- .expect(201);
524
-
525
- expect(response.body).toMatchObject({
526
- name: userData.name,
527
- email: userData.email,
528
- });
529
- expect(response.body).toHaveProperty('id');
530
- expect(response.body).not.toHaveProperty('password');
531
- });
532
-
533
- it('should return 400 if email is invalid', async () => {
534
- const userData = {
535
- name: 'John Doe',
536
- email: 'invalid-email',
537
- password: 'password123',
538
- };
539
-
540
- const response = await request(app)
541
- .post('/api/users')
542
- .send(userData)
543
- .expect(400);
544
-
545
- expect(response.body).toHaveProperty('error');
546
- });
547
-
548
- it('should return 409 if email already exists', async () => {
549
- const userData = {
550
- name: 'John Doe',
551
- email: 'john@example.com',
552
- password: 'password123',
553
- };
554
-
555
- await request(app).post('/api/users').send(userData);
556
-
557
- const response = await request(app)
558
- .post('/api/users')
559
- .send(userData)
560
- .expect(409);
561
-
562
- expect(response.body.error).toContain('already exists');
563
- });
564
- });
565
-
566
- describe('GET /api/users/:id', () => {
567
- it('should get user by id', async () => {
568
- const createResponse = await request(app)
569
- .post('/api/users')
570
- .send({
571
- name: 'John Doe',
572
- email: 'john@example.com',
573
- password: 'password123',
574
- });
575
-
576
- const userId = createResponse.body.id;
577
-
578
- const response = await request(app)
579
- .get(`/api/users/${userId}`)
580
- .expect(200);
581
-
582
- expect(response.body).toMatchObject({
583
- id: userId,
584
- name: 'John Doe',
585
- email: 'john@example.com',
586
- });
587
- });
588
-
589
- it('should return 404 if user not found', async () => {
590
- await request(app)
591
- .get('/api/users/999')
592
- .expect(404);
593
- });
594
- });
595
-
596
- describe('Authentication', () => {
597
- it('should require authentication for protected routes', async () => {
598
- await request(app)
599
- .get('/api/users/me')
600
- .expect(401);
601
- });
602
-
603
- it('should allow access with valid token', async () => {
604
- // Create user and login
605
- await request(app)
606
- .post('/api/users')
607
- .send({
608
- name: 'John Doe',
609
- email: 'john@example.com',
610
- password: 'password123',
611
- });
612
-
613
- const loginResponse = await request(app)
614
- .post('/api/auth/login')
615
- .send({
616
- email: 'john@example.com',
617
- password: 'password123',
618
- });
619
-
620
- const token = loginResponse.body.token;
621
-
622
- const response = await request(app)
623
- .get('/api/users/me')
624
- .set('Authorization', `Bearer ${token}`)
625
- .expect(200);
626
-
627
- expect(response.body.email).toBe('john@example.com');
628
- });
629
- });
630
- });
631
- ```
632
-
633
- ### Pattern 2: Database Integration Tests
634
-
635
- ```typescript
636
- // tests/integration/user.repository.test.ts
637
- import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
638
- import { Pool } from 'pg';
639
- import { UserRepository } from '../../src/repositories/user.repository';
640
-
641
- describe('UserRepository Integration Tests', () => {
642
- let pool: Pool;
643
- let repository: UserRepository;
644
-
645
- beforeAll(async () => {
646
- pool = new Pool({
647
- host: 'localhost',
648
- port: 5432,
649
- database: 'test_db',
650
- user: 'test_user',
651
- password: 'test_password',
652
- });
653
-
654
- repository = new UserRepository(pool);
655
-
656
- // Create tables
657
- await pool.query(`
658
- CREATE TABLE IF NOT EXISTS users (
659
- id SERIAL PRIMARY KEY,
660
- name VARCHAR(255) NOT NULL,
661
- email VARCHAR(255) UNIQUE NOT NULL,
662
- password VARCHAR(255) NOT NULL,
663
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
664
- )
665
- `);
666
- });
667
-
668
- afterAll(async () => {
669
- await pool.query('DROP TABLE IF EXISTS users');
670
- await pool.end();
671
- });
672
-
673
- beforeEach(async () => {
674
- await pool.query('TRUNCATE TABLE users CASCADE');
675
- });
676
-
677
- it('should create a user', async () => {
678
- const user = await repository.create({
679
- name: 'John Doe',
680
- email: 'john@example.com',
681
- password: 'hashed_password',
682
- });
683
-
684
- expect(user).toHaveProperty('id');
685
- expect(user.name).toBe('John Doe');
686
- expect(user.email).toBe('john@example.com');
687
- });
688
-
689
- it('should find user by email', async () => {
690
- await repository.create({
691
- name: 'John Doe',
692
- email: 'john@example.com',
693
- password: 'hashed_password',
694
- });
695
-
696
- const user = await repository.findByEmail('john@example.com');
697
-
698
- expect(user).toBeTruthy();
699
- expect(user?.name).toBe('John Doe');
700
- });
701
-
702
- it('should return null if user not found', async () => {
703
- const user = await repository.findByEmail('nonexistent@example.com');
704
- expect(user).toBeNull();
705
- });
706
- });
707
- ```
708
-
709
- ## Frontend Testing with Testing Library
710
-
711
- ### Pattern 1: React Component Testing
712
-
713
- ```typescript
714
- // components/UserForm.tsx
715
- import { useState } from 'react';
716
-
717
- interface Props {
718
- onSubmit: (user: { name: string; email: string }) => void;
719
- }
720
-
721
- export function UserForm({ onSubmit }: Props) {
722
- const [name, setName] = useState('');
723
- const [email, setEmail] = useState('');
724
-
725
- const handleSubmit = (e: React.FormEvent) => {
726
- e.preventDefault();
727
- onSubmit({ name, email });
728
- };
729
-
730
- return (
731
- <form onSubmit={handleSubmit}>
732
- <input
733
- type="text"
734
- placeholder="Name"
735
- value={name}
736
- onChange={(e) => setName(e.target.value)}
737
- data-testid="name-input"
738
- />
739
- <input
740
- type="email"
741
- placeholder="Email"
742
- value={email}
743
- onChange={(e) => setEmail(e.target.value)}
744
- data-testid="email-input"
745
- />
746
- <button type="submit">Submit</button>
747
- </form>
748
- );
749
- }
750
-
751
- // components/UserForm.test.tsx
752
- import { render, screen, fireEvent } from '@testing-library/react';
753
- import { describe, it, expect, vi } from 'vitest';
754
- import { UserForm } from './UserForm';
755
-
756
- describe('UserForm', () => {
757
- it('should render form inputs', () => {
758
- render(<UserForm onSubmit={vi.fn()} />);
759
-
760
- expect(screen.getByPlaceholderText('Name')).toBeInTheDocument();
761
- expect(screen.getByPlaceholderText('Email')).toBeInTheDocument();
762
- expect(screen.getByRole('button', { name: 'Submit' })).toBeInTheDocument();
763
- });
764
-
765
- it('should update input values', () => {
766
- render(<UserForm onSubmit={vi.fn()} />);
767
-
768
- const nameInput = screen.getByTestId('name-input') as HTMLInputElement;
769
- const emailInput = screen.getByTestId('email-input') as HTMLInputElement;
770
-
771
- fireEvent.change(nameInput, { target: { value: 'John Doe' } });
772
- fireEvent.change(emailInput, { target: { value: 'john@example.com' } });
773
-
774
- expect(nameInput.value).toBe('John Doe');
775
- expect(emailInput.value).toBe('john@example.com');
776
- });
777
-
778
- it('should call onSubmit with form data', () => {
779
- const onSubmit = vi.fn();
780
- render(<UserForm onSubmit={onSubmit} />);
781
-
782
- fireEvent.change(screen.getByTestId('name-input'), {
783
- target: { value: 'John Doe' },
784
- });
785
- fireEvent.change(screen.getByTestId('email-input'), {
786
- target: { value: 'john@example.com' },
787
- });
788
- fireEvent.click(screen.getByRole('button', { name: 'Submit' }));
789
-
790
- expect(onSubmit).toHaveBeenCalledWith({
791
- name: 'John Doe',
792
- email: 'john@example.com',
793
- });
794
- });
795
- });
796
- ```
797
-
798
- ### Pattern 2: Testing Hooks
799
-
800
- ```typescript
801
- // hooks/useCounter.ts
802
- import { useState, useCallback } from 'react';
803
-
804
- export function useCounter(initialValue = 0) {
805
- const [count, setCount] = useState(initialValue);
806
-
807
- const increment = useCallback(() => setCount((c) => c + 1), []);
808
- const decrement = useCallback(() => setCount((c) => c - 1), []);
809
- const reset = useCallback(() => setCount(initialValue), [initialValue]);
810
-
811
- return { count, increment, decrement, reset };
812
- }
813
-
814
- // hooks/useCounter.test.ts
815
- import { renderHook, act } from '@testing-library/react';
816
- import { describe, it, expect } from 'vitest';
817
- import { useCounter } from './useCounter';
818
-
819
- describe('useCounter', () => {
820
- it('should initialize with default value', () => {
821
- const { result } = renderHook(() => useCounter());
822
- expect(result.current.count).toBe(0);
823
- });
824
-
825
- it('should initialize with custom value', () => {
826
- const { result } = renderHook(() => useCounter(10));
827
- expect(result.current.count).toBe(10);
828
- });
829
-
830
- it('should increment count', () => {
831
- const { result } = renderHook(() => useCounter());
832
-
833
- act(() => {
834
- result.current.increment();
835
- });
836
-
837
- expect(result.current.count).toBe(1);
838
- });
839
-
840
- it('should decrement count', () => {
841
- const { result } = renderHook(() => useCounter(5));
842
-
843
- act(() => {
844
- result.current.decrement();
845
- });
846
-
847
- expect(result.current.count).toBe(4);
848
- });
849
-
850
- it('should reset to initial value', () => {
851
- const { result } = renderHook(() => useCounter(10));
852
-
853
- act(() => {
854
- result.current.increment();
855
- result.current.increment();
856
- });
857
-
858
- expect(result.current.count).toBe(12);
859
-
860
- act(() => {
861
- result.current.reset();
862
- });
863
-
864
- expect(result.current.count).toBe(10);
865
- });
866
- });
867
- ```
868
-
869
- ## Test Fixtures and Factories
870
-
871
- ```typescript
872
- // tests/fixtures/user.fixture.ts
873
- import { faker } from '@faker-js/faker';
874
-
875
- export function createUserFixture(overrides?: Partial<User>): User {
876
- return {
877
- id: faker.string.uuid(),
878
- name: faker.person.fullName(),
879
- email: faker.internet.email(),
880
- createdAt: faker.date.past(),
881
- ...overrides,
882
- };
883
- }
884
-
885
- export function createUsersFixture(count: number): User[] {
886
- return Array.from({ length: count }, () => createUserFixture());
887
- }
888
-
889
- // Usage in tests
890
- import { createUserFixture, createUsersFixture } from '../fixtures/user.fixture';
891
-
892
- describe('UserService', () => {
893
- it('should process user', () => {
894
- const user = createUserFixture({ name: 'John Doe' });
895
- // Use user in test
896
- });
897
-
898
- it('should handle multiple users', () => {
899
- const users = createUsersFixture(10);
900
- // Use users in test
901
- });
902
- });
903
- ```
904
-
905
- ## Snapshot Testing
906
-
907
- ```typescript
908
- // components/UserCard.test.tsx
909
- import { render } from '@testing-library/react';
910
- import { describe, it, expect } from 'vitest';
911
- import { UserCard } from './UserCard';
912
-
913
- describe('UserCard', () => {
914
- it('should match snapshot', () => {
915
- const user = {
916
- id: '1',
917
- name: 'John Doe',
918
- email: 'john@example.com',
919
- avatar: 'https://example.com/avatar.jpg',
920
- };
921
-
922
- const { container } = render(<UserCard user={user} />);
923
-
924
- expect(container.firstChild).toMatchSnapshot();
925
- });
926
-
927
- it('should match snapshot with loading state', () => {
928
- const { container } = render(<UserCard loading />);
929
- expect(container.firstChild).toMatchSnapshot();
930
- });
931
- });
932
- ```
933
-
934
- ## Coverage Reports
935
-
936
- ```typescript
937
- // package.json
938
- {
939
- "scripts": {
940
- "test": "vitest",
941
- "test:coverage": "vitest --coverage",
942
- "test:ui": "vitest --ui"
943
- }
944
- }
945
- ```
946
-
947
- ## Best Practices
948
-
949
- 1. **Follow AAA Pattern**: Arrange, Act, Assert
950
- 2. **One assertion per test**: Or logically related assertions
951
- 3. **Descriptive test names**: Should describe what is being tested
952
- 4. **Use beforeEach/afterEach**: For setup and teardown
953
- 5. **Mock external dependencies**: Keep tests isolated
954
- 6. **Test edge cases**: Not just happy paths
955
- 7. **Avoid implementation details**: Test behavior, not implementation
956
- 8. **Use test factories**: For consistent test data
957
- 9. **Keep tests fast**: Mock slow operations
958
- 10. **Write tests first (TDD)**: When possible
959
- 11. **Maintain test coverage**: Aim for 80%+ coverage
960
- 12. **Use TypeScript**: For type-safe tests
961
- 13. **Test error handling**: Not just success cases
962
- 14. **Use data-testid sparingly**: Prefer semantic queries
963
- 15. **Clean up after tests**: Prevent test pollution
964
-
965
- ## Common Patterns
966
-
967
- ### Test Organization
968
-
969
- ```typescript
970
- describe('UserService', () => {
971
- describe('createUser', () => {
972
- it('should create user successfully', () => {});
973
- it('should throw error if email exists', () => {});
974
- it('should hash password', () => {});
975
- });
976
-
977
- describe('updateUser', () => {
978
- it('should update user', () => {});
979
- it('should throw error if not found', () => {});
980
- });
981
- });
982
- ```
983
-
984
- ### Testing Promises
985
-
986
- ```typescript
987
- // Using async/await
988
- it('should fetch user', async () => {
989
- const user = await service.fetchUser('1');
990
- expect(user).toBeDefined();
991
- });
992
-
993
- // Testing rejections
994
- it('should throw error', async () => {
995
- await expect(service.fetchUser('invalid')).rejects.toThrow('Not found');
996
- });
997
- ```
998
-
999
- ### Testing Timers
1000
-
1001
- ```typescript
1002
- import { vi } from 'vitest';
1003
-
1004
- it('should call function after delay', () => {
1005
- vi.useFakeTimers();
1006
-
1007
- const callback = vi.fn();
1008
- setTimeout(callback, 1000);
1009
-
1010
- expect(callback).not.toHaveBeenCalled();
1011
-
1012
- vi.advanceTimersByTime(1000);
1013
-
1014
- expect(callback).toHaveBeenCalled();
1015
-
1016
- vi.useRealTimers();
1017
- });
1018
- ```
1019
-
1020
- ## Resources
1021
-
1022
- - **Jest Documentation**: https://jestjs.io/
1023
- - **Vitest Documentation**: https://vitest.dev/
1024
- - **Testing Library**: https://testing-library.com/
1025
- - **Kent C. Dodds Testing Blog**: https://kentcdodds.com/blog/