bun-test-mocking
Use for mock functions in Bun tests, spyOn, mock.module, implementations, and test doubles.
What this skill does
# Bun Test Mocking
Bun provides Jest-compatible mocking with `mock()`, `spyOn()`, and module mocking.
## Mock Functions
```typescript
import { test, expect, mock } from "bun:test";
// Create mock function
const fn = mock(() => "original");
test("mock function", () => {
fn("arg1", "arg2");
expect(fn).toHaveBeenCalled();
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith("arg1", "arg2");
});
```
### jest.fn() Compatibility
```typescript
import { test, expect, jest } from "bun:test";
const fn = jest.fn(() => "value");
test("jest.fn works", () => {
const result = fn();
expect(result).toBe("value");
expect(fn).toHaveBeenCalled();
});
```
## Mock Return Values
```typescript
const fn = mock();
// Return value once
fn.mockReturnValueOnce("first");
fn.mockReturnValueOnce("second");
// Permanent return value
fn.mockReturnValue("default");
// Promise returns
fn.mockResolvedValue("resolved");
fn.mockResolvedValueOnce("once");
fn.mockRejectedValue(new Error("fail"));
fn.mockRejectedValueOnce(new Error("once"));
```
## Mock Implementations
```typescript
const fn = mock();
// Set implementation
fn.mockImplementation((x) => x * 2);
// One-time implementation
fn.mockImplementationOnce((x) => x * 10);
// Chain implementations
fn
.mockImplementationOnce(() => "first")
.mockImplementationOnce(() => "second")
.mockImplementation(() => "default");
```
## Spy on Methods
```typescript
import { test, expect, spyOn } from "bun:test";
const obj = {
method: () => "original",
};
test("spy on method", () => {
const spy = spyOn(obj, "method");
obj.method();
expect(spy).toHaveBeenCalled();
expect(obj.method()).toBe("original"); // Still works
// Override implementation
spy.mockImplementation(() => "mocked");
expect(obj.method()).toBe("mocked");
// Restore
spy.mockRestore();
expect(obj.method()).toBe("original");
});
```
## Mock Modules
```typescript
import { test, expect, mock } from "bun:test";
// Mock entire module
mock.module("./utils", () => ({
add: mock(() => 999),
subtract: mock(() => 0),
}));
// Now imports use mocked version
import { add } from "./utils";
test("mocked module", () => {
expect(add(1, 2)).toBe(999);
});
```
### Mock Node Modules
```typescript
mock.module("axios", () => ({
default: {
get: mock(() => Promise.resolve({ data: "mocked" })),
post: mock(() => Promise.resolve({ data: "created" })),
},
}));
```
### Mock with Factory
```typescript
mock.module("./config", () => {
return {
API_URL: "http://test.local",
DEBUG: true,
};
});
```
## Mock Assertions
```typescript
const fn = mock();
fn("a", "b");
fn("c", "d");
// Call count
expect(fn).toHaveBeenCalled();
expect(fn).toHaveBeenCalledTimes(2);
// Call arguments
expect(fn).toHaveBeenCalledWith("a", "b");
expect(fn).toHaveBeenLastCalledWith("c", "d");
expect(fn).toHaveBeenNthCalledWith(1, "a", "b");
// Return values
fn.mockReturnValue("result");
fn();
expect(fn).toHaveReturned();
expect(fn).toHaveReturnedWith("result");
expect(fn).toHaveReturnedTimes(1);
```
## Mock Properties
```typescript
const fn = mock(() => "value");
fn("arg1");
fn("arg2");
// Access call info
fn.mock.calls; // [["arg1"], ["arg2"]]
fn.mock.results; // [{ type: "return", value: "value" }, ...]
fn.mock.lastCall; // ["arg2"]
// Clear history
fn.mockClear(); // Clear calls, keep implementation
fn.mockReset(); // Clear calls + implementation
fn.mockRestore(); // Restore original (for spies)
```
## Common Patterns
### Mock Fetch
```typescript
import { test, expect, spyOn } from "bun:test";
test("mock fetch", async () => {
const spy = spyOn(global, "fetch").mockResolvedValue(
new Response(JSON.stringify({ data: "mocked" }))
);
const response = await fetch("/api/data");
const json = await response.json();
expect(json.data).toBe("mocked");
expect(spy).toHaveBeenCalledWith("/api/data");
spy.mockRestore();
});
```
### Mock Console
```typescript
test("mock console", () => {
const spy = spyOn(console, "log");
console.log("test message");
expect(spy).toHaveBeenCalledWith("test message");
spy.mockRestore();
});
```
### Mock Class Methods
```typescript
class UserService {
async getUser(id: string) {
// Real implementation
}
}
test("mock class method", () => {
const service = new UserService();
const spy = spyOn(service, "getUser").mockResolvedValue({
id: "1",
name: "Test User",
});
const user = await service.getUser("1");
expect(user.name).toBe("Test User");
expect(spy).toHaveBeenCalledWith("1");
});
```
## Common Errors
| Error | Cause | Fix |
|-------|-------|-----|
| `Cannot spy on undefined` | Property doesn't exist | Check property name |
| `Not a function` | Trying to mock non-function | Use correct mock approach |
| `Already mocked` | Double mocking | Use mockRestore first |
| `Module not found` | Wrong module path | Check path in mock.module |
## When to Load References
Load `references/mock-api.md` when:
- Complete mock/spy API reference
- Advanced mocking patterns
Load `references/module-mocking.md` when:
- Complex module mocking
- Hoisting behavior details
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.