[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77MSRCT6D31QVB86PFZHR4V":3,"skill-same:01M77MSRCT6D31QVB86PFZHR4V":52},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M77MSRCT6D31QVB86PFZHR4V","javascript-testing-patterns",null,"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\u002FTypeScript tests, setting up test infrastructure, or implementing TDD\u002FBDD workflows.","Reihantt6\u002Fsns-myagent","Reihantt6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F219822095?v=4","01M77KK94PV8B7C2D9XWXNS8DJ","Mohamad Reihan tegar prasetya","01M77KK958QFMTHYXGXFV7KZ79",2,"MIT","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fjavascript-testing-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: javascript-testing-patterns\ndescription: 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\u002FTypeScript tests, setting up test infrastructure, or implementing TDD\u002FBDD workflows.\n---\n\n# JavaScript Testing Patterns\n\nComprehensive guide for implementing robust testing strategies in JavaScript\u002FTypeScript applications using modern testing frameworks and best practices.\n\n## When to Use This Skill\n\n- Setting up test infrastructure for new projects\n- Writing unit tests for functions and classes\n- Creating integration tests for APIs and services\n- Implementing end-to-end tests for user flows\n- Mocking external dependencies and APIs\n- Testing React, Vue, or other frontend components\n- Implementing test-driven development (TDD)\n- Setting up continuous testing in CI\u002FCD pipelines\n\n## Testing Frameworks\n\n### Jest - Full-Featured Testing Framework\n\n**Setup:**\n\n```typescript\n\u002F\u002F jest.config.ts\nimport type { Config } from \"jest\";\n\nconst config: Config = {\n  preset: \"ts-jest\",\n  testEnvironment: \"node\",\n  roots: [\"\u003CrootDir>\u002Fsrc\"],\n  testMatch: [\"**\u002F__tests__\u002F**\u002F*.ts\", \"**\u002F?(*.)+(spec|test).ts\"],\n  collectCoverageFrom: [\n    \"src\u002F**\u002F*.ts\",\n    \"!src\u002F**\u002F*.d.ts\",\n    \"!src\u002F**\u002F*.interface.ts\",\n  ],\n  coverageThreshold: {\n    global: {\n      branches: 80,\n      functions: 80,\n      lines: 80,\n      statements: 80,\n    },\n  },\n  setupFilesAfterEnv: [\"\u003CrootDir>\u002Fsrc\u002Ftest\u002Fsetup.ts\"],\n};\n\nexport default config;\n```\n\n### Vitest - Fast, Vite-Native Testing\n\n**Setup:**\n\n```typescript\n\u002F\u002F vitest.config.ts\nimport { defineConfig } from \"vitest\u002Fconfig\";\n\nexport default defineConfig({\n  test: {\n    globals: true,\n    environment: \"node\",\n    coverage: {\n      provider: \"v8\",\n      reporter: [\"text\", \"json\", \"html\"],\n      exclude: [\"**\u002F*.d.ts\", \"**\u002F*.config.ts\", \"**\u002Fdist\u002F**\"],\n    },\n    setupFiles: [\".\u002Fsrc\u002Ftest\u002Fsetup.ts\"],\n  },\n});\n```\n\n## Unit Testing Patterns\n\n### Pattern 1: Testing Pure Functions\n\n```typescript\n\u002F\u002F utils\u002Fcalculator.ts\nexport function add(a: number, b: number): number {\n  return a + b;\n}\n\nexport function divide(a: number, b: number): number {\n  if (b === 0) {\n    throw new Error(\"Division by zero\");\n  }\n  return a \u002F b;\n}\n\n\u002F\u002F utils\u002Fcalculator.test.ts\nimport { describe, it, expect } from \"vitest\";\nimport { add, divide } from \".\u002Fcalculator\";\n\ndescribe(\"Calculator\", () => {\n  describe(\"add\", () => {\n    it(\"should add two positive numbers\", () => {\n      expect(add(2, 3)).toBe(5);\n    });\n\n    it(\"should add negative numbers\", () => {\n      expect(add(-2, -3)).toBe(-5);\n    });\n\n    it(\"should handle zero\", () => {\n      expect(add(0, 5)).toBe(5);\n      expect(add(5, 0)).toBe(5);\n    });\n  });\n\n  describe(\"divide\", () => {\n    it(\"should divide two numbers\", () => {\n      expect(divide(10, 2)).toBe(5);\n    });\n\n    it(\"should handle decimal results\", () => {\n      expect(divide(5, 2)).toBe(2.5);\n    });\n\n    it(\"should throw error when dividing by zero\", () => {\n      expect(() => divide(10, 0)).toThrow(\"Division by zero\");\n    });\n  });\n});\n```\n\n### Pattern 2: Testing Classes\n\n```typescript\n\u002F\u002F services\u002Fuser.service.ts\nexport class UserService {\n  private users: Map\u003Cstring, User> = new Map();\n\n  create(user: User): User {\n    if (this.users.has(user.id)) {\n      throw new Error(\"User already exists\");\n    }\n    this.users.set(user.id, user);\n    return user;\n  }\n\n  findById(id: string): User | undefined {\n    return this.users.get(id);\n  }\n\n  update(id: string, updates: Partial\u003CUser>): User {\n    const user = this.users.get(id);\n    if (!user) {\n      throw new Error(\"User not found\");\n    }\n    const updated = { ...user, ...updates };\n    this.users.set(id, updated);\n    return updated;\n  }\n\n  delete(id: string): boolean {\n    return this.users.delete(id);\n  }\n}\n\n\u002F\u002F services\u002Fuser.service.test.ts\nimport { describe, it, expect, beforeEach } from \"vitest\";\nimport { UserService } from \".\u002Fuser.service\";\n\ndescribe(\"UserService\", () => {\n  let service: UserService;\n\n  beforeEach(() => {\n    service = new UserService();\n  });\n\n  describe(\"create\", () => {\n    it(\"should create a new user\", () => {\n      const user = { id: \"1\", name: \"John\", email: \"john@example.com\" };\n      const created = service.create(user);\n\n      expect(created).toEqual(user);\n      expect(service.findById(\"1\")).toEqual(user);\n    });\n\n    it(\"should throw error if user already exists\", () => {\n      const user = { id: \"1\", name: \"John\", email: \"john@example.com\" };\n      service.create(user);\n\n      expect(() => service.create(user)).toThrow(\"User already exists\");\n    });\n  });\n\n  describe(\"update\", () => {\n    it(\"should update existing user\", () => {\n      const user = { id: \"1\", name: \"John\", email: \"john@example.com\" };\n      service.create(user);\n\n      const updated = service.update(\"1\", { name: \"Jane\" });\n\n      expect(updated.name).toBe(\"Jane\");\n      expect(updated.email).toBe(\"john@example.com\");\n    });\n\n    it(\"should throw error if user not found\", () => {\n      expect(() => service.update(\"999\", { name: \"Jane\" })).toThrow(\n        \"User not found\",\n      );\n    });\n  });\n});\n```\n\n### Pattern 3: Testing Async Functions\n\n```typescript\n\u002F\u002F services\u002Fapi.service.ts\nexport class ApiService {\n  async fetchUser(id: string): Promise\u003CUser> {\n    const response = await fetch(`https:\u002F\u002Fapi.example.com\u002Fusers\u002F${id}`);\n    if (!response.ok) {\n      throw new Error(\"User not found\");\n    }\n    return response.json();\n  }\n\n  async createUser(user: CreateUserDTO): Promise\u003CUser> {\n    const response = await fetch(\"https:\u002F\u002Fapi.example.com\u002Fusers\", {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application\u002Fjson\" },\n      body: JSON.stringify(user),\n    });\n    return response.json();\n  }\n}\n\n\u002F\u002F services\u002Fapi.service.test.ts\nimport { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { ApiService } from \".\u002Fapi.service\";\n\n\u002F\u002F Mock fetch globally\nglobal.fetch = vi.fn();\n\ndescribe(\"ApiService\", () => {\n  let service: ApiService;\n\n  beforeEach(() => {\n    service = new ApiService();\n    vi.clearAllMocks();\n  });\n\n  describe(\"fetchUser\", () => {\n    it(\"should fetch user successfully\", async () => {\n      const mockUser = { id: \"1\", name: \"John\", email: \"john@example.com\" };\n\n      (fetch as any).mockResolvedValueOnce({\n        ok: true,\n        json: async () => mockUser,\n      });\n\n      const user = await service.fetchUser(\"1\");\n\n      expect(user).toEqual(mockUser);\n      expect(fetch).toHaveBeenCalledWith(\"https:\u002F\u002Fapi.example.com\u002Fusers\u002F1\");\n    });\n\n    it(\"should throw error if user not found\", async () => {\n      (fetch as any).mockResolvedValueOnce({\n        ok: false,\n      });\n\n      await expect(service.fetchUser(\"999\")).rejects.toThrow(\"User not found\");\n    });\n  });\n\n  describe(\"createUser\", () => {\n    it(\"should create user successfully\", async () => {\n      const newUser = { name: \"John\", email: \"john@example.com\" };\n      const createdUser = { id: \"1\", ...newUser };\n\n      (fetch as any).mockResolvedValueOnce({\n        ok: true,\n        json: async () => createdUser,\n      });\n\n      const user = await service.createUser(newUser);\n\n      expect(user).toEqual(createdUser);\n      expect(fetch).toHaveBeenCalledWith(\n        \"https:\u002F\u002Fapi.example.com\u002Fusers\",\n        expect.objectContaining({\n          method: \"POST\",\n          body: JSON.stringify(newUser),\n        }),\n      );\n    });\n  });\n});\n```\n\n## Mocking Patterns\n\n### Pattern 1: Mocking Modules\n\n```typescript\n\u002F\u002F services\u002Femail.service.ts\nimport nodemailer from \"nodemailer\";\n\nexport class EmailService {\n  private transporter = nodemailer.createTransport({\n    host: process.env.SMTP_HOST,\n    port: 587,\n    auth: {\n      user: process.env.SMTP_USER,\n      pass: process.env.SMTP_PASS,\n    },\n  });\n\n  async sendEmail(to: string, subject: string, html: string) {\n    await this.transporter.sendMail({\n      from: process.env.EMAIL_FROM,\n      to,\n      subject,\n      html,\n    });\n  }\n}\n\n\u002F\u002F services\u002Femail.service.test.ts\nimport { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { EmailService } from \".\u002Femail.service\";\n\nvi.mock(\"nodemailer\", () => ({\n  default: {\n    createTransport: vi.fn(() => ({\n      sendMail: vi.fn().mockResolvedValue({ messageId: \"123\" }),\n    })),\n  },\n}));\n\ndescribe(\"EmailService\", () => {\n  let service: EmailService;\n\n  beforeEach(() => {\n    service = new EmailService();\n  });\n\n  it(\"should send email successfully\", async () => {\n    await service.sendEmail(\n      \"test@example.com\",\n      \"Test Subject\",\n      \"\u003Cp>Test Body\u003C\u002Fp>\",\n    );\n\n    expect(service[\"transporter\"].sendMail).toHaveBeenCalledWith(\n      expect.objectContaining({\n        to: \"test@example.com\",\n        subject: \"Test Subject\",\n      }),\n    );\n  });\n});\n```\n\n### Pattern 2: Dependency Injection for Testing\n\n```typescript\n\u002F\u002F services\u002Fuser.service.ts\nexport interface IUserRepository {\n  findById(id: string): Promise\u003CUser | null>;\n  create(user: User): Promise\u003CUser>;\n}\n\nexport class UserService {\n  constructor(private userRepository: IUserRepository) {}\n\n  async getUser(id: string): Promise\u003CUser> {\n    const user = await this.userRepository.findById(id);\n    if (!user) {\n      throw new Error(\"User not found\");\n    }\n    return user;\n  }\n\n  async createUser(userData: CreateUserDTO): Promise\u003CUser> {\n    \u002F\u002F Business logic here\n    const user = { id: generateId(), ...userData };\n    return this.userRepository.create(user);\n  }\n}\n\n\u002F\u002F services\u002Fuser.service.test.ts\nimport { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { UserService, IUserRepository } from \".\u002Fuser.service\";\n\ndescribe(\"UserService\", () => {\n  let service: UserService;\n  let mockRepository: IUserRepository;\n\n  beforeEach(() => {\n    mockRepository = {\n      findById: vi.fn(),\n      create: vi.fn(),\n    };\n    service = new UserService(mockRepository);\n  });\n\n  describe(\"getUser\", () => {\n    it(\"should return user if found\", async () => {\n      const mockUser = { id: \"1\", name: \"John\", email: \"john@example.com\" };\n      vi.mocked(mockRepository.findById).mockResolvedValue(mockUser);\n\n      const user = await service.getUser(\"1\");\n\n      expect(user).toEqual(mockUser);\n      expect(mockRepository.findById).toHaveBeenCalledWith(\"1\");\n    });\n\n    it(\"should throw error if user not found\", async () => {\n      vi.mocked(mockRepository.findById).mockResolvedValue(null);\n\n      await expect(service.getUser(\"999\")).rejects.toThrow(\"User not found\");\n    });\n  });\n\n  describe(\"createUser\", () => {\n    it(\"should create user successfully\", async () => {\n      const userData = { name: \"John\", email: \"john@example.com\" };\n      const createdUser = { id: \"1\", ...userData };\n\n      vi.mocked(mockRepository.create).mockResolvedValue(createdUser);\n\n      const user = await service.createUser(userData);\n\n      expect(user).toEqual(createdUser);\n      expect(mockRepository.create).toHaveBeenCalled();\n    });\n  });\n});\n```\n\n### Pattern 3: Spying on Functions\n\n```typescript\n\u002F\u002F utils\u002Flogger.ts\nexport const logger = {\n  info: (message: string) => console.log(`INFO: ${message}`),\n  error: (message: string) => console.error(`ERROR: ${message}`),\n};\n\n\u002F\u002F services\u002Forder.service.ts\nimport { logger } from \"..\u002Futils\u002Flogger\";\n\nexport class OrderService {\n  async processOrder(orderId: string): Promise\u003Cvoid> {\n    logger.info(`Processing order ${orderId}`);\n    \u002F\u002F Process order logic\n    logger.info(`Order ${orderId} processed successfully`);\n  }\n}\n\n\u002F\u002F services\u002Forder.service.test.ts\nimport { describe, it, expect, vi, beforeEach, afterEach } from \"vitest\";\nimport { OrderService } from \".\u002Forder.service\";\nimport { logger } from \"..\u002Futils\u002Flogger\";\n\ndescribe(\"OrderService\", () => {\n  let service: OrderService;\n  let loggerSpy: any;\n\n  beforeEach(() => {\n    service = new OrderService();\n    loggerSpy = vi.spyOn(logger, \"info\");\n  });\n\n  afterEach(() => {\n    loggerSpy.mockRestore();\n  });\n\n  it(\"should log order processing\", async () => {\n    await service.processOrder(\"123\");\n\n    expect(loggerSpy).toHaveBeenCalledWith(\"Processing order 123\");\n    expect(loggerSpy).toHaveBeenCalledWith(\"Order 123 processed successfully\");\n    expect(loggerSpy).toHaveBeenCalledTimes(2);\n  });\n});\n```\n\n## Integration Testing\n\nIntegration tests verify real database operations and HTTP endpoints using `supertest` and a test database instance. Always truncate tables in `beforeEach` and tear down in `afterAll`.\n\nFor full API integration test examples (supertest + PostgreSQL) and database repository integration tests, see [references\u002Fadvanced-testing-patterns.md](references\u002Fadvanced-testing-patterns.md).\n\n## Frontend Testing with Testing Library\n\nTest React components by rendering them and querying by role, placeholder, or test ID. Test hooks with `renderHook` + `act`. Prefer semantic queries (`getByRole`, `getByPlaceholderText`) over `data-testid`.\n\nFor complete React component test examples (UserForm, hooks with `renderHook`\u002F`act`), see [references\u002Fadvanced-testing-patterns.md](references\u002Fadvanced-testing-patterns.md).\n\n## Test Fixtures and Factories\n\nUse `@faker-js\u002Ffaker` to generate realistic test data factories. Factories accept optional `overrides` so tests can set only the fields they care about:\n\n```typescript\n\u002F\u002F tests\u002Ffixtures\u002Fuser.fixture.ts\nimport { faker } from \"@faker-js\u002Ffaker\";\n\nexport function createUserFixture(overrides?: Partial\u003CUser>): User {\n  return {\n    id: faker.string.uuid(),\n    name: faker.person.fullName(),\n    email: faker.internet.email(),\n    createdAt: faker.date.past(),\n    ...overrides,\n  };\n}\n```\n\nFor snapshot testing, coverage configuration, test organization patterns, promise testing, and timer mocking, see [references\u002Fadvanced-testing-patterns.md](references\u002Fadvanced-testing-patterns.md).\n\n## Best Practices\n\n1. **Follow AAA Pattern**: Arrange, Act, Assert\n2. **One assertion per test**: Or logically related assertions\n3. **Descriptive test names**: Should describe what is being tested\n4. **Use beforeEach\u002FafterEach**: For setup and teardown\n5. **Mock external dependencies**: Keep tests isolated\n6. **Test edge cases**: Not just happy paths\n7. **Avoid implementation details**: Test behavior, not implementation\n8. **Use test factories**: For consistent test data\n9. **Keep tests fast**: Mock slow operations\n10. **Write tests first (TDD)**: When possible\n11. **Maintain test coverage**: Aim for 80%+ coverage\n12. **Use TypeScript**: For type-safe tests\n13. **Test error handling**: Not just success cases\n14. **Use data-testid sparingly**: Prefer semantic queries\n15. **Clean up after tests**: Prevent test pollution\n","# JavaScript Testing Patterns\n\nComprehensive guide for implementing robust testing strategies in JavaScript\u002FTypeScript applications using modern testing frameworks and best practices.\n\n## When to Use This Skill\n\n- Setting up test infrastructure for new projects\n- Writing unit tests for functions and classes\n- Creating integration tests for APIs and services\n- Implementing end-to-end tests for user flows\n- Mocking external dependencies and APIs\n- Testing React, Vue, or other frontend components\n- Implementing test-driven development (TDD)\n- Setting up continuous testing in CI\u002FCD pipelines\n\n## Testing Frameworks\n\n### Jest - Full-Featured Testing Framework\n\n**Setup:**\n\n```typescript\n\u002F\u002F jest.config.ts\nimport type { Config } from \"jest\";\n\nconst config: Config = {\n  preset: \"ts-jest\",\n  testEnvironment: \"node\",\n  roots: [\"\u003CrootDir>\u002Fsrc\"],\n  testMatch: [\"**\u002F__tests__\u002F**\u002F*.ts\", \"**\u002F?(*.)+(spec|test).ts\"],\n  collectCoverageFrom: [\n    \"src\u002F**\u002F*.ts\",\n    \"!src\u002F**\u002F*.d.ts\",\n    \"!src\u002F**\u002F*.interface.ts\",\n  ],\n  coverageThreshold: {\n    global: {\n      branches: 80,\n      functions: 80,\n      lines: 80,\n      statements: 80,\n    },\n  },\n  setupFilesAfterEnv: [\"\u003CrootDir>\u002Fsrc\u002Ftest\u002Fsetup.ts\"],\n};\n\nexport default config;\n```\n\n### Vitest - Fast, Vite-Native Testing\n\n**Setup:**\n\n```typescript\n\u002F\u002F vitest.config.ts\nimport { defineConfig } from \"vitest\u002Fconfig\";\n\nexport default defineConfig({\n  test: {\n    globals: true,\n    environment: \"node\",\n    coverage: {\n      provider: \"v8\",\n      reporter: [\"text\", \"json\", \"html\"],\n      exclude: [\"**\u002F*.d.ts\", \"**\u002F*.config.ts\", \"**\u002Fdist\u002F**\"],\n    },\n    setupFiles: [\".\u002Fsrc\u002Ftest\u002Fsetup.ts\"],\n  },\n});\n```\n\n## Unit Testing Patterns\n\n### Pattern 1: Testing Pure Functions\n\n```typescript\n\u002F\u002F utils\u002Fcalculator.ts\nexport function add(a: number, b: number): number {\n  return a + b;\n}\n\nexport function divide(a: number, b: number): number {\n  if (b === 0) {\n    throw new Error(\"Division by zero\");\n  }\n  return a \u002F b;\n}\n\n\u002F\u002F utils\u002Fcalculator.test.ts\nimport { describe, it, expect } from \"vitest\";\nimport { add, divide } from \".\u002Fcalculator\";\n\ndescribe(\"Calculator\", () => {\n  describe(\"add\", () => {\n    it(\"should add two positive numbers\", () => {\n      expect(add(2, 3)).toBe(5);\n    });\n\n    it(\"should add negative numbers\", () => {\n      expect(add(-2, -3)).toBe(-5);\n    });\n\n    it(\"should handle zero\", () => {\n      expect(add(0, 5)).toBe(5);\n      expect(add(5, 0)).toBe(5);\n    });\n  });\n\n  describe(\"divide\", () => {\n    it(\"should divide two numbers\", () => {\n      expect(divide(10, 2)).toBe(5);\n    });\n\n    it(\"should handle decimal results\", () => {\n      expect(divide(5, 2)).toBe(2.5);\n    });\n\n    it(\"should throw error when dividing by zero\", () => {\n      expect(() => divide(10, 0)).toThrow(\"Division by zero\");\n    });\n  });\n});\n```\n\n### Pattern 2: Testing Classes\n\n```typescript\n\u002F\u002F services\u002Fuser.service.ts\nexport class UserService {\n  private users: Map\u003Cstring, User> = new Map();\n\n  create(user: User): User {\n    if (this.users.has(user.id)) {\n      throw new Error(\"User already exists\");\n    }\n    this.users.set(user.id, user);\n    return user;\n  }\n\n  findById(id: string): User | undefined {\n    return this.users.get(id);\n  }\n\n  update(id: string, updates: Partial\u003CUser>): User {\n    const user = this.users.get(id);\n    if (!user) {\n      throw new Error(\"User not found\");\n    }\n    const updated = { ...user, ...updates };\n    this.users.set(id, updated);\n    return updated;\n  }\n\n  delete(id: string): boolean {\n    return this.users.delete(id);\n  }\n}\n\n\u002F\u002F services\u002Fuser.service.test.ts\nimport { describe, it, expect, beforeEach } from \"vitest\";\nimport { UserService } from \".\u002Fuser.service\";\n\ndescribe(\"UserService\", () => {\n  let service: UserService;\n\n  beforeEach(() => {\n    service = new UserService();\n  });\n\n  describe(\"create\", () => {\n    it(\"should create a new user\", () => {\n      const user = { id: \"1\", name: \"John\", email: \"john@example.com\" };\n      const created = service.create(user);\n\n      expect(created).toEqual(user);\n      expect(service.findById(\"1\")).toEqual(user);\n    });\n\n    it(\"should throw error if user already exists\", () => {\n      const user = { id: \"1\", name: \"John\", email: \"john@example.com\" };\n      service.create(user);\n\n      expect(() => service.create(user)).toThrow(\"User already exists\");\n    });\n  });\n\n  describe(\"update\", () => {\n    it(\"should update existing user\", () => {\n      const user = { id: \"1\", name: \"John\", email: \"john@example.com\" };\n      service.create(user);\n\n      const updated = service.update(\"1\", { name: \"Jane\" });\n\n      expect(updated.name).toBe(\"Jane\");\n      expect(updated.email).toBe(\"john@example.com\");\n    });\n\n    it(\"should throw error if user not found\", () => {\n      expect(() => service.update(\"999\", { name: \"Jane\" })).toThrow(\n        \"User not found\",\n      );\n    });\n  });\n});\n```\n\n### Pattern 3: Testing Async Functions\n\n```typescript\n\u002F\u002F services\u002Fapi.service.ts\nexport class ApiService {\n  async fetchUser(id: string): Promise\u003CUser> {\n    const response = await fetch(`https:\u002F\u002Fapi.example.com\u002Fusers\u002F${id}`);\n    if (!response.ok) {\n      throw new Error(\"User not found\");\n    }\n    return response.json();\n  }\n\n  async createUser(user: CreateUserDTO): Promise\u003CUser> {\n    const response = await fetch(\"https:\u002F\u002Fapi.example.com\u002Fusers\", {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application\u002Fjson\" },\n      body: JSON.stringify(user),\n    });\n    return response.json();\n  }\n}\n\n\u002F\u002F services\u002Fapi.service.test.ts\nimport { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { ApiService } from \".\u002Fapi.service\";\n\n\u002F\u002F Mock fetch globally\nglobal.fetch = vi.fn();\n\ndescribe(\"ApiService\", () => {\n  let service: ApiService;\n\n  beforeEach(() => {\n    service = new ApiService();\n    vi.clearAllMocks();\n  });\n\n  describe(\"fetchUser\", () => {\n    it(\"should fetch user successfully\", async () => {\n      const mockUser = { id: \"1\", name: \"John\", email: \"john@example.com\" };\n\n      (fetch as any).mockResolvedValueOnce({\n        ok: true,\n        json: async () => mockUser,\n      });\n\n      const user = await service.fetchUser(\"1\");\n\n      expect(user).toEqual(mockUser);\n      expect(fetch).toHaveBeenCalledWith(\"https:\u002F\u002Fapi.example.com\u002Fusers\u002F1\");\n    });\n\n    it(\"should throw error if user not found\", async () => {\n      (fetch as any).mockResolvedValueOnce({\n        ok: false,\n      });\n\n      await expect(service.fetchUser(\"999\")).rejects.toThrow(\"User not found\");\n    });\n  });\n\n  describe(\"createUser\", () => {\n    it(\"should create user successfully\", async () => {\n      const newUser = { name: \"John\", email: \"john@example.com\" };\n      const createdUser = { id: \"1\", ...newUser };\n\n      (fetch as any).mockResolvedValueOnce({\n        ok: true,\n        json: async () => createdUser,\n      });\n\n      const user = await service.createUser(newUser);\n\n      expect(user).toEqual(createdUser);\n      expect(fetch).toHaveBeenCalledWith(\n        \"https:\u002F\u002Fapi.example.com\u002Fusers\",\n        expect.objectContaining({\n          method: \"POST\",\n          body: JSON.stringify(newUser),\n        }),\n      );\n    });\n  });\n});\n```\n\n## Mocking Patterns\n\n### Pattern 1: Mocking Modules\n\n```typescript\n\u002F\u002F services\u002Femail.service.ts\nimport nodemailer from \"nodemailer\";\n\nexport class EmailService {\n  private transporter = nodemailer.createTransport({\n    host: process.env.SMTP_HOST,\n    port: 587,\n    auth: {\n      user: process.env.SMTP_USER,\n      pass: process.env.SMTP_PASS,\n    },\n  });\n\n  async sendEmail(to: string, subject: string, html: string) {\n    await this.transporter.sendMail({\n      from: process.env.EMAIL_FROM,\n      to,\n      subject,\n      html,\n    });\n  }\n}\n\n\u002F\u002F services\u002Femail.service.test.ts\nimport { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { EmailService } from \".\u002Femail.service\";\n\nvi.mock(\"nodemailer\", () => ({\n  default: {\n    createTransport: vi.fn(() => ({\n      sendMail: vi.fn().mockResolvedValue({ messageId: \"123\" }),\n    })),\n  },\n}));\n\ndescribe(\"EmailService\", () => {\n  let service: EmailService;\n\n  beforeEach(() => {\n    service = new EmailService();\n  });\n\n  it(\"should send email successfully\", async () => {\n    await service.sendEmail(\n      \"test@example.com\",\n      \"Test Subject\",\n      \"\u003Cp>Test Body\u003C\u002Fp>\",\n    );\n\n    expect(service[\"transporter\"].sendMail).toHaveBeenCalledWith(\n      expect.objectContaining({\n        to: \"test@example.com\",\n        subject: \"Test Subject\",\n      }),\n    );\n  });\n});\n```\n\n### Pattern 2: Dependency Injection for Testing\n\n```typescript\n\u002F\u002F services\u002Fuser.service.ts\nexport interface IUserRepository {\n  findById(id: string): Promise\u003CUser | null>;\n  create(user: User): Promise\u003CUser>;\n}\n\nexport class UserService {\n  constructor(private userRepository: IUserRepository) {}\n\n  async getUser(id: string): Promise\u003CUser> {\n    const user = await this.userRepository.findById(id);\n    if (!user) {\n      throw new Error(\"User not found\");\n    }\n    return user;\n  }\n\n  async createUser(userData: CreateUserDTO): Promise\u003CUser> {\n    \u002F\u002F Business logic here\n    const user = { id: generateId(), ...userData };\n    return this.userRepository.create(user);\n  }\n}\n\n\u002F\u002F services\u002Fuser.service.test.ts\nimport { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { UserService, IUserRepository } from \".\u002Fuser.service\";\n\ndescribe(\"UserService\", () => {\n  let service: UserService;\n  let mockRepository: IUserRepository;\n\n  beforeEach(() => {\n    mockRepository = {\n      findById: vi.fn(),\n      create: vi.fn(),\n    };\n    service = new UserService(mockRepository);\n  });\n\n  describe(\"getUser\", () => {\n    it(\"should return user if found\", async () => {\n      const mockUser = { id: \"1\", name: \"John\", email: \"john@example.com\" };\n      vi.mocked(mockRepository.findById).mockResolvedValue(mockUser);\n\n      const user = await service.getUser(\"1\");\n\n      expect(user).toEqual(mockUser);\n      expect(mockRepository.findById).toHaveBeenCalledWith(\"1\");\n    });\n\n    it(\"should throw error if user not found\", async () => {\n      vi.mocked(mockRepository.findById).mockResolvedValue(null);\n\n      await expect(service.getUser(\"999\")).rejects.toThrow(\"User not found\");\n    });\n  });\n\n  describe(\"createUser\", () => {\n    it(\"should create user successfully\", async () => {\n      const userData = { name: \"John\", email: \"john@example.com\" };\n      const createdUser = { id: \"1\", ...userData };\n\n      vi.mocked(mockRepository.create).mockResolvedValue(createdUser);\n\n      const user = await service.createUser(userData);\n\n      expect(user).toEqual(createdUser);\n      expect(mockRepository.create).toHaveBeenCalled();\n    });\n  });\n});\n```\n\n### Pattern 3: Spying on Functions\n\n```typescript\n\u002F\u002F utils\u002Flogger.ts\nexport const logger = {\n  info: (message: string) => console.log(`INFO: ${message}`),\n  error: (message: string) => console.error(`ERROR: ${message}`),\n};\n\n\u002F\u002F services\u002Forder.service.ts\nimport { logger } from \"..\u002Futils\u002Flogger\";\n\nexport class OrderService {\n  async processOrder(orderId: string): Promise\u003Cvoid> {\n    logger.info(`Processing order ${orderId}`);\n    \u002F\u002F Process order logic\n    logger.info(`Order ${orderId} processed successfully`);\n  }\n}\n\n\u002F\u002F services\u002Forder.service.test.ts\nimport { describe, it, expect, vi, beforeEach, afterEach } from \"vitest\";\nimport { OrderService } from \".\u002Forder.service\";\nimport { logger } from \"..\u002Futils\u002Flogger\";\n\ndescribe(\"OrderService\", () => {\n  let service: OrderService;\n  let loggerSpy: any;\n\n  beforeEach(() => {\n    service = new OrderService();\n    loggerSpy = vi.spyOn(logger, \"info\");\n  });\n\n  afterEach(() => {\n    loggerSpy.mockRestore();\n  });\n\n  it(\"should log order processing\", async () => {\n    await service.processOrder(\"123\");\n\n    expect(loggerSpy).toHaveBeenCalledWith(\"Processing order 123\");\n    expect(loggerSpy).toHaveBeenCalledWith(\"Order 123 processed successfully\");\n    expect(loggerSpy).toHaveBeenCalledTimes(2);\n  });\n});\n```\n\n## Integration Testing\n\nIntegration tests verify real database operations and HTTP endpoints using `supertest` and a test database instance. Always truncate tables in `beforeEach` and tear down in `afterAll`.\n\nFor full API integration test examples (supertest + PostgreSQL) and database repository integration tests, see [references\u002Fadvanced-testing-patterns.md](references\u002Fadvanced-testing-patterns.md).\n\n## Frontend Testing with Testing Library\n\nTest React components by rendering them and querying by role, placeholder, or test ID. Test hooks with `renderHook` + `act`. Prefer semantic queries (`getByRole`, `getByPlaceholderText`) over `data-testid`.\n\nFor complete React component test examples (UserForm, hooks with `renderHook`\u002F`act`), see [references\u002Fadvanced-testing-patterns.md](references\u002Fadvanced-testing-patterns.md).\n\n## Test Fixtures and Factories\n\nUse `@faker-js\u002Ffaker` to generate realistic test data factories. Factories accept optional `overrides` so tests can set only the fields they care about:\n\n```typescript\n\u002F\u002F tests\u002Ffixtures\u002Fuser.fixture.ts\nimport { faker } from \"@faker-js\u002Ffaker\";\n\nexport function createUserFixture(overrides?: Partial\u003CUser>): User {\n  return {\n    id: faker.string.uuid(),\n    name: faker.person.fullName(),\n    email: faker.internet.email(),\n    createdAt: faker.date.past(),\n    ...overrides,\n  };\n}\n```\n\nFor snapshot testing, coverage configuration, test organization patterns, promise testing, and timer mocking, see [references\u002Fadvanced-testing-patterns.md](references\u002Fadvanced-testing-patterns.md).\n\n## Best Practices\n\n1. **Follow AAA Pattern**: Arrange, Act, Assert\n2. **One assertion per test**: Or logically related assertions\n3. **Descriptive test names**: Should describe what is being tested\n4. **Use beforeEach\u002FafterEach**: For setup and teardown\n5. **Mock external dependencies**: Keep tests isolated\n6. **Test edge cases**: Not just happy paths\n7. **Avoid implementation details**: Test behavior, not implementation\n8. **Use test factories**: For consistent test data\n9. **Keep tests fast**: Mock slow operations\n10. **Write tests first (TDD)**: When possible\n11. **Maintain test coverage**: Aim for 80%+ coverage\n12. **Use TypeScript**: For type-safe tests\n13. **Test error handling**: Not just success cases\n14. **Use data-testid sparingly**: Prefer semantic queries\n15. **Clean up after tests**: Prevent test pollution\n",{"name":5,"description":7},"main","58843b159d7a4050d6b785a98b908cce505c0b92",".agents\u002Fskills\u002Fjavascript-testing-patterns",0,"https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent","https:\u002F\u002Fgithub.com\u002FReihantt6","reihsns.web.id","2026-08-19 20:08:18",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add Reihantt6\u002Fsns-myagent --skill javascript-testing-patterns",{"tool":38,"command":39},"bunx","bunx skills add Reihantt6\u002Fsns-myagent --skill javascript-testing-patterns",{"tool":41,"command":42},"pnpm","pnpm dlx skills add Reihantt6\u002Fsns-myagent --skill javascript-testing-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fjavascript-testing-patterns\u002FSKILL.md",true,[46],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"references\u002Fadvanced-testing-patterns.md","REFERENCE","参考文档",12837,"https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fjavascript-testing-patterns\u002Freferences\u002Fadvanced-testing-patterns.md",[53,60,67,74,81,88],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M77XDCYZ407XYMF2T4P6F7VT","youtube-transcript","Extract transcripts from YouTube videos. Use when the user asks for a transcript, subtitles, or captions of a YouTube video and provides a YouTube URL (youtube.com\u002Fwatch?v=, youtu.be\u002F, or similar). Supports output with or without timestamps.","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fyoutube-transcript\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M77XD7PBC98J6MXGJJ2TJ8DX","youtube-thumbnail-design","YouTube thumbnail design with specific dimensions, contrast rules, and mobile preview optimization. Covers safe zones, text placement, face expression psychology, and A\u002FB testing. Use for: YouTube thumbnails, video cover images, click-through optimization. Triggers: youtube thumbnail, thumbnail design, video thumbnail, click through rate, ctr optimization, youtube cover, video cover image, thumbnail maker, thumbnail tips, youtube design, video preview image","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fyoutube-thumbnail-design\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M77XD2541C8HXJ6RHYZP4NGJ","youtube-short-maker","Make YouTube Shorts that hold attention with Pexo — vertical 9:16, fast-paced, hook in the first 3 seconds. Describe your topic and Pexo writes the script, generates the shots, picks the models, and assembles a finished Short with music and captions. Use for YouTube Shorts: \"youtube short\", \"make a youtube short\", \"shorts video\", \"short-form video\". NOT for long-form or landscape video.","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fyoutube-short-maker\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M77XCXKVSYK7KTZ3PQBVVGFD","xcode-project-setup","Safely modifies Xcode projects (.pbxproj) to add Swift Packages and link files. Use this skill whenever an iOS project needs dependencies installed (e.g. Firebase, Alamofire).","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fxcode-project-setup\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M77XCR1DV8ZQK2NHWKVY4EWX","x402","Set up Browser Use Cloud payments with x402 — pay per request from a crypto wallet (USDC on Base mainnet), no signup or API key. Two setups it works out up front — \"just use it\" (set up a wallet so you or Claude Code can run cloud browser tasks paid from the wallet — Claude writes and runs throwaway scripts, nothing touches your codebase) or \"build it in\" (install the SDK and write the key + code into your project). Walks through wallet setup, funding, .env, and a ~$1 test run. Use when the user asks about x402, pay-per-use, USDC payments, or wants Browser Use Cloud without an API key. For the free-tier signup (reverse-CAPTCHA → API key), use `browser-use cloud signup` or the `cloud` skill instead.","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fx402\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M77XCMD3R3ZBZQQSW6E0793B","x-twitter-scraper","Build GitHub Copilot workflows with Xquik X API SDKs, REST endpoints, hosted Apify Actor runs, MCP tools, TweetClaw OpenClaw plugin installs, signed webhooks, tweet search, user lookup, follower exports, media actions, and agent automation.","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fx-twitter-scraper\u002FSKILL.md",[],[]]