بنقرة واحدة
test-jest
Use this skill when writing or fixing unit tests with Jest (TypeScript/JavaScript).
التثبيت باستخدام Codex أو Claude انسخ هذا Prompt والصقه في Codex أو Claude أو مساعد آخر ليراجع صفحة Skill ويثبّتها لك.
القائمة
Use this skill when writing or fixing unit tests with Jest (TypeScript/JavaScript).
التثبيت باستخدام Codex أو Claude انسخ هذا Prompt والصقه في Codex أو Claude أو مساعد آخر ليراجع صفحة Skill ويثبّتها لك.
استنادا إلى تصنيف SOC المهني
| name | test-jest |
| description | Use this skill when writing or fixing unit tests with Jest (TypeScript/JavaScript). |
Jest is a widely-used JavaScript testing framework with built-in mocking, assertions, and coverage support.
Jest is in use when:
package.json devDependencies includes jest or ts-jest or @types/jestjest.config.js, jest.config.ts, or jest.config.json exists.spec.ts, .test.ts, .spec.js, or .test.js extensionspackage.json has a "jest" configuration keysrc/
foo.ts # production file
foo.spec.ts # test file (co-located)
# OR
__tests__/
foo.test.ts # alternative location
Match the existing project convention.
import { myFunction } from './myModule'
describe('myModule', () => {
beforeEach(() => {
jest.clearAllMocks()
})
describe('myFunction', () => {
it('should return expected value for valid input', () => {
// Arrange
const input = 'hello'
// Build
const result = myFunction(input)
// Assert
expect(result).toBe('HELLO')
})
it('should throw for invalid input', () => {
expect(() => myFunction(null)).toThrow('Input must not be null')
})
})
})
jest.mock('./dependency', () => ({
fetchData: jest.fn().mockResolvedValue({ id: 1, name: 'test' }),
}))
const mockFn = jest.fn().mockReturnValue(42)
const mockAsync = jest.fn().mockResolvedValue({ ok: true })
const mockRejected = jest.fn().mockRejectedValue(new Error('fail'))
const spy = jest.spyOn(obj, 'method').mockReturnValue('mocked')
jest.mock('./heavyModule') // auto-mocks all exports
beforeEach(() => {
jest.clearAllMocks() // clear call counts and instances
jest.resetAllMocks() // clear + reset implementations to undefined
jest.restoreAllMocks() // restore jest.spyOn originals
})
it('should resolve promise', async () => {
const result = await someAsyncFunction()
expect(result).toEqual({ success: true })
})
it('should reject promise', async () => {
await expect(someAsyncFunction()).rejects.toThrow('error message')
})
// With done callback (legacy)
it('legacy callback test', (done) => {
fetchData((data) => {
expect(data).toBe('ok')
done()
})
})
jest.useFakeTimers()
it('should debounce', () => {
const fn = jest.fn()
debounce(fn, 500)()
jest.advanceTimersByTime(500)
expect(fn).toHaveBeenCalledTimes(1)
})
afterEach(() => jest.useRealTimers())
expect(value).toBe(42) // strict equality (Object.is)
expect(value).toEqual({ a: 1 }) // deep equality
expect(value).toStrictEqual({ a: 1 }) // deep + checks undefined properties
expect(value).toBeNull()
expect(value).toBeUndefined()
expect(value).toBeDefined()
expect(value).toBeTruthy()
expect(value).toBeFalsy()
expect(array).toHaveLength(3)
expect(array).toContain('item')
expect(object).toHaveProperty('key', 'value')
expect(fn).toHaveBeenCalledWith('arg')
expect(fn).toHaveBeenCalledTimes(2)
expect(fn).toHaveBeenNthCalledWith(1, 'first arg')
expect(fn).not.toHaveBeenCalled()
expect(value).toMatchSnapshot()
expect(value).toMatchInlineSnapshot(`"expected"`)
With ts-jest:
// jest.config.json
{
"preset": "ts-jest",
"testEnvironment": "node",
"roots": ["<rootDir>/src"]
}
With @swc/jest (faster):
{
"transform": {
"^.+\.(t|j)s$": "@swc/jest"
}
}
# Run all tests
npx jest
# Run with coverage
npx jest --coverage
# Run specific file
npx jest src/foo.spec.ts
# Run tests matching pattern
npx jest --testNamePattern="myFunction"
# Watch mode
npx jest --watch
Configure in jest.config.js:
module.exports = {
collectCoverageFrom: ['src/**/*.ts', '!src/**/*.spec.ts'],
coverageThreshold: {
global: { lines: 80 }
}
}
jest.mock() is hoisted to the top of the file by Babel/Jest — don't rely on variable initialization orderjest.fn() over raw functions for spying — raw functions can't be trackedtoEqual does deep equality; toBe uses Object.is (like ===) — use toEqual for objects/arraysbeforeEach to prevent test pollution across test cases@types/jest is installed or use import type { jest } from '@jest/globals'Use `author-caveman` to write Caveman English.
Use `author-agent` to get OpenCode Agent Authoring when writing or reviewing OpenCode agent markdown.
Use `author-command` to get OpenCode Command Authoring when writing or reviewing OpenCode command markdown.
Use `author-rules` to write `AGENTS.md` files.
Use `author-skill` to get Skill File Authoring when you need to review/write skill files for agents.
Use `design-prd` to get Product Requirements when planning any feature or to understand project business requirements, user roles, and success criteria.