What it does
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
Skills ZICQ category:Writing & Research javascript-testing-patterns
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.
Official URL:skills.sh
Intro in this page language first. The official description stays in its original wording; we do not rewrite SKILL.md.
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
This Skill
Per Agent Skills progressive disclosure: name and description load at startup (~100 tokens); the full SKILL.md body loads when the skill activates; scripts/, references/, and assets/ load only as needed. This file's sections: JavaScript Testing Patterns; When to Use This Skill; Testing Frameworks; Jest - Full-Featured Testing Framework; Vitest - Fast, Vite-Native Testing; Unit Testing Patterns.
File analysis: besides SKILL.md, the body references references/advanced-testing-patterns.md. Those resources load on demand. The body is about 532 lines, above the spec’s 500-line guidance; agents still load it in full on activation.
JavaScript Testing PatternsWhen to Use This SkillTesting FrameworksJest - Full-Featured Testing FrameworkVitest - Fast, Vite-Native TestingUnit Testing PatternsPattern 1: Testing Pure FunctionsPattern 2: Testing ClassesPattern 3: Testing Async FunctionsMocking PatternsPattern 1: Mocking ModulesPattern 2: Dependency Injection for Testing
Source category:skills.sh agent-skill
namejavascript-testing-patternsdescriptionreferences/advanced-testing-patterns.mdThese paths are extracted from the text. Check the upstream package to verify the files exist.
Invocation syntax and available tools depend on your Agent client. Client integration guide ↗
Choose the target agent and installation scope, keep referenced package files, then verify the skill appears in the client's catalog.
This skill references supporting files. Retrieve the complete directory from the source; copying SKILL.md alone may leave missing dependencies.
Copy these instructions to a compatible agent and confirm the target directory matches your client.
Install the agent skill "javascript-testing-patterns" into my project. The full SKILL.md and official description are at https://zicq.com/en/skills/skl-86bd172a0d6dcffb-Javascript-Testing-Patterns.html Save it as .cursor/skills/javascript-testing-patterns/SKILL.md or .claude/skills/javascript-testing-patterns/SKILL.md and keep the frontmatter name and description exactly as-is. This skill also ships scripts/, references/, or assets/ — fetch the whole folder from https://github.com/wshobson/agents instead of creating only a SKILL.md.
Requires Node.js and npx. First inspect the repository's skill list to confirm the name.
npx skills add 'https://github.com/wshobson/agents' --list
npx skills add 'https://github.com/wshobson/agents' --skill 'javascript-testing-patterns'
The CLI lets you choose the agent interactively. The default scope is the project; use -g for user scope. Confirm package availability with the discovery command, then use npx skills list to inspect installed skills.
Test Body
", ); expect(service["transporter"].sendMail).toHaveBeenCalledWith( expect.objectContaining({ to: "[email protected]", subject: "Test Subject", }), ); }); }); ``` ### Pattern 2: Dependency Injection for Testing ```typescript // services/user.service.ts export interface IUserRepository { findById(id: string): Promise; create(user: User): Promise; } export class UserService { constructor(private userRepository: IUserRepository) {} async getUser(id: string): Promise { const user = await this.userRepository.findById(id); if (!user) { throw new Error("User not found"); } return user; } async createUser(userData: CreateUserDTO): Promise { // Business logic here const user = { id: generateId(), ...userData }; return this.userRepository.create(user); } } // services/user.service.test.ts import { describe, it, expect, vi, beforeEach } from "vitest"; import { UserService, IUserRepository } from "./user.service"; describe("UserService", () => { let service: UserService; let mockRepository: IUserRepository; beforeEach(() => { mockRepository = { findById: vi.fn(), create: vi.fn(), }; service = new UserService(mockRepository); }); describe("getUser", () => { it("should return user if found", async () => { const mockUser = { id: "1", name: "John", email: "[email protected]" }; vi.mocked(mockRepository.findById).mockResolvedValue(mockUser); const user = await service.getUser("1"); expect(user).toEqual(mockUser); expect(mockRepository.findById).toHaveBeenCalledWith("1"); }); it("should throw error if user not found", async () => { vi.mocked(mockRepository.findById).mockResolvedValue(null); await expect(service.getUser("999")).rejects.toThrow("User not found"); }); }); describe("createUser", () => { it("should create user successfully", async () => { const userData = { name: "John", email: "[email protected]" }; const createdUser = { id: "1", ...userData }; vi.mocked(mockRepository.create).mockResolvedValue(createdUser); const user = await service.createUser(userData); expect(user).toEqual(createdUser); expect(mockRepository.create).toHaveBeenCalled(); }); }); }); ``` ### Pattern 3: Spying on Functions ```typescript // utils/logger.ts export const logger = { info: (message: string) => console.log(`INFO: ${message}`), error: (message: string) => console.error(`ERROR: ${message}`), }; // services/order.service.ts import { logger } from "../utils/logger"; export class OrderService { async processOrder(orderId: string): Promise { logger.info(`Processing order ${orderId}`); // Process order logic logger.info(`Order ${orderId} processed successfully`); } } // services/order.service.test.ts import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { OrderService } from "./order.service"; import { logger } from "../utils/logger"; describe("OrderService", () => { let service: OrderService; let loggerSpy: any; beforeEach(() => { service = new OrderService(); loggerSpy = vi.spyOn(logger, "info"); }); afterEach(() => { loggerSpy.mockRestore(); }); it("should log order processing", async () => { await service.processOrder("123"); expect(loggerSpy).toHaveBeenCalledWith("Processing order 123"); expect(loggerSpy).toHaveBeenCalledWith("Order 123 processed successfully"); expect(loggerSpy).toHaveBeenCalledTimes(2); }); }); ``` ## Integration Testing Integration 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`. For full API integration test examples (supertest + PostgreSQL) and database repository integration tests, see [references/advanced-testing-patterns.md](references/advanced-testing-patterns.md). ## Frontend Testing with Testing Library Test 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`. For complete React component test examples (UserForm, hooks with `renderHook`/`act`), see [references/advanced-testing-patterns.md](references/advanced-testing-patterns.md). ## Test Fixtures and Factories Use `@faker-js/faker` to generate realistic test data factories. Factories accept optional `overrides` so tests can set only the fields they care about: ```typescript // tests/fixtures/user.fixture.ts import { faker } from "@faker-js/faker"; export function createUserFixture(overrides?: Partial): User { return { id: faker.string.uuid(), name: faker.person.fullName(), email: faker.internet.email(), createdAt: faker.date.past(), ...overrides, }; } ``` For snapshot testing, coverage configuration, test organization patterns, promise testing, and timer mocking, see [references/advanced-testing-patterns.md](references/advanced-testing-patterns.md). ## Best Practices 1. **Follow AAA Pattern**: Arrange, Act, Assert 2. **One assertion per test**: Or logically related assertions 3. **Descriptive test names**: Should describe what is being tested 4. **Use beforeEach/afterEach**: For setup and teardown 5. **Mock external dependencies**: Keep tests isolated 6. **Test edge cases**: Not just happy paths 7. **Avoid implementation details**: Test behavior, not implementation 8. **Use test factories**: For consistent test data 9. **Keep tests fast**: Mock slow operations 10. **Write tests first (TDD)**: When possible 11. **Maintain test coverage**: Aim for 80%+ coverage 12. **Use TypeScript**: For type-safe tests 13. **Test error handling**: Not just success cases 14. **Use data-testid sparingly**: Prefer semantic queries 15. **Clean up after tests**: Prevent test pollutionWriting & Research
Remove signs of AI-generated writing from text. Use when editing or reviewing text to make it sound more natural and human-written. Based on…
Writing & Research
Default web search for OpenClaw. Search the web across 10 engines — Google, Reddit, GitHub, arXiv, Hacker News, and more — using Prismfy. Fr…
Writing & Research
Monitor blogs and RSS/Atom feeds for updates using the blogwatcher CLI.
Writing & Research
AI-optimized web search using Tavily Search API. Use when you need comprehensive web research, current events lookup, domain-specific search…