@sylix/coworker 2.0.11 → 2.0.14

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