npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

jest-ts

v1.1.22

Published

High-performance Jest TypeScript transpiler powered by esbuild, supporting type checking, intelligent caching, and one-click initialization.

Readme

jest-ts

基于 esbuild 的高性能 Jest TypeScript 转译工具,解决传统 ts-jest 转译慢的痛点,支持类型检查、智能缓存,并提供 一键初始化 功能,让 TypeScript 项目接入 Jest 测试更高效、更简单。

核心特性

  • ⚡️ 极速转译:依托 esbuild 引擎,TS/TSX 转译速度比 ts-jest 快 5-10 倍,毫秒级响应
  • 🔍 按需类型检查:基于官方 TypeScript API 实现类型检查,与转译解耦,不阻塞测试执行
  • 📦 智能缓存:根据代码内容、配置、包版本生成哈希缓存,避免重复转译,二次测试速度翻倍
  • 🚀 一键初始化npx jest-ts init 自动生成配置文件、示例代码和脚本,零手动操作
  • 🎯 多场景适配:支持 Node.js/浏览器(jsdom)测试环境,兼容 CommonJS/ES 模块,适配 React/Vue 等框架

安装

通过 npm、yarn 或 pnpm 安装(需搭配 jesttypescript 使用):

# npm
npm install jest-ts jest typescript --save-dev

# yarn
yarn add jest-ts jest typescript --dev

# pnpm
pnpm add jest-ts jest typescript -D

依赖要求

  • peerDependenciesjest ≥28.0.0typescript ≥5.0.0
  • 运行环境:Node.js ≥16.0.0(适配 esbuild 最低要求)

快速开始(推荐:一键初始化)

通过 npx jest-ts init 自动生成所有基础文件,无需手动配置,3 步完成测试环境搭建:

1. 执行初始化命令

在项目根目录运行:

npx jest-ts init

初始化流程说明

  • 自动生成 配置文件jest.config.js(集成 jest-ts 预设)、tsconfig.json(适配 Jest 模块系统)
  • 自动生成 示例代码
    • 业务代码:src/__test__/math.ts(简单数学工具函数)
    • 测试用例:__tests__/math.test.ts(Jest 测试语法示例)
  • 自动更新 package.json
    • 新增 test/test:watch 脚本(无需手动写脚本)
    • 若文件不存在,生成基础依赖声明

交互提示

若目标文件已存在(如现有 jest.config.js),会提示是否覆盖,避免误删用户数据:

⚠️  /your-project/jest.config.js 已存在,是否覆盖?(y/N) 

2. 安装依赖

初始化完成后,安装项目依赖(若 package.json 已生成,直接执行):

# npm
npm install

# yarn
yarn install

# pnpm
pnpm install

3. 运行测试

执行测试命令,验证环境是否正常:

# 运行所有测试
npm test

# 监听文件变更,实时重跑测试(开发时推荐)
npm run test:watch

预期测试结果(成功示例)

 PASS  __tests__/math.test.ts
  src/__test__/math.ts
    add
      ✓ 应该正确计算两个正整数的和 (2ms)
      ✓ 应该正确计算负数与正数的和
      ✓ 传入非数字参数时应该抛出 TypeError
    multiply
      ✓ 应该正确计算两个数的乘积
      ✓ 传入非数字参数时应该抛出 TypeError
  ✓ subtract 应该正确计算两个数的差 (1ms)

Test Suites: 1 passed, 1 total
Tests:       6 passed, 6 total
Time:        0.85s

手动配置(进阶场景)

若需自定义配置(不使用 init 命令),可手动创建以下文件:

1. Jest 配置(jest.config.js)

/** @type {import('jest').Config} */
module.exports = {
  // 核心:使用 jest-ts 预设
  preset: "jest-ts/jest-preset",
  // 测试环境:Node.js 用 "node",浏览器项目用 "jsdom"
  testEnvironment: "node",
  // 测试文件匹配规则(可自定义)
  testMatch: [
    "**/__tests__/**/*.+(ts|tsx|js)",
    "**/?(*.)+(spec|test).+(ts|tsx|js)"
  ]
};

2. TypeScript 配置(tsconfig.json)

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS", // 适配 Jest 模块系统
    "moduleResolution": "Node",
    "strict": true, // 开启严格类型检查(推荐)
    "esModuleInterop": true, // 兼容 CommonJS/ES 模块
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true, // 支持导入 JSON 文件
    "outDir": "dist", // 业务代码编译目录(可选)
    "rootDir": "." // 包含 src 和 __tests__ 目录
  },
  "include": ["src/**/*", "__tests__/**/*"], // 覆盖业务代码和测试文件
  "exclude": ["node_modules"]
}

自定义配置

通过 Jest 的 globals 配置项扩展 jest-ts 功能,支持以下参数:

| 配置项 | 类型 | 默认值 | 说明 | |-----------------|-----------|---------------------------------|----------------------------------------------------------------------| | typeCheck | boolean | false | 开启 TypeScript 类型检查(错误会阻断测试执行,底层执行 tsc --noEmit) | | cacheDirectory| string | ./node_modules/.cache/jest-ts | 缓存文件存储目录(删除该目录可强制刷新缓存) | | tsconfigPath | string | ./tsconfig.json | 自定义 TypeScript 配置文件路径(如测试专用 tsconfig.test.json) | | esbuildOptions| object | { target: "es2020", loader: {} } | 传递给 esbuild 的转译选项(支持所有 esbuild TransformOptions) |

自定义配置示例(React 项目)

/** @type {import('jest').Config} */
module.exports = {
  preset: "jest-ts/jest-preset",
  testEnvironment: "jsdom", // 浏览器环境(React 项目需用 jsdom)
  globals: {
    "jest-ts": {
      typeCheck: true, // 开启类型检查
      cacheDirectory: "./.cache/jest-ts", // 自定义缓存目录
      tsconfigPath: "./tsconfig.test.json", // 测试专用 TS 配置
      esbuildOptions: {
        target: "es2022", // 适配现代浏览器
        loader: {
          ".tsx": "tsx", // 支持 React TSX 语法
          ".svg": "dataurl", // 处理 SVG 文件(转译为 Data URL)
          ".css": "css" // 处理 CSS 文件(需配合 `jest-css-modules`)
        },
        define: {
          "process.env.NODE_ENV": '"test"' // 注入测试环境变量
        }
      }
    }
  },
  // 模块别名(与 tsconfig.json 保持一致)
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1"
  },
  // 忽略 node_modules 中的特定包转译
  transformIgnorePatterns: ["/node_modules/(?!@mui/).+\\.tsx$"]
};

API 参考(进阶使用)

jest-ts 导出核心转译能力,支持脱离预设直接集成到自定义流程中。

1. transformTsCode

手动转译 TypeScript 代码,返回转译后的 JS 代码和 SourceMap(用于调试)。

类型定义

import type { JestTsOptions } from "jest-ts";

/**
 * 手动转译 TypeScript 代码
 * @param filename 文件路径(用于识别文件类型,如 .ts/.tsx)
 * @param code 待转译的 TypeScript 源代码
 * @param globals 自定义配置(同 Jest globals 中的 "jest-ts" 选项)
 * @returns 转译结果(JS 代码 + SourceMap)
 */
export function transformTsCode(
  filename: string,
  code: string,
  globals?: { "jest-ts"?: Partial<JestTsOptions> }
): { code: string; map: string };

使用示例

import { transformTsCode } from "jest-ts";

// 待转译的 TS 代码
const tsCode = `
  export interface User {
    id: number;
    name: string;
  }
  export const formatUser = (user: User): string => \`\${user.id}-\${user.name}\`;
`;

// 执行转译
const { code: jsCode, map } = transformTsCode("user.ts", tsCode, {
  "jest-ts": { typeCheck: true }
});

console.log(jsCode);
// 输出(类型定义被移除,保留函数逻辑):
// export const formatUser = (user) => `${user.id}-${user.name}`;

2. transformer

Jest 转换器对象,可直接用于 Jest 的 transform 配置(替代预设,适合高度自定义场景)。

使用示例

/** @type {import('jest').Config} */
module.exports = {
  // 不使用预设,直接指定转换器
  transform: {
    "^.+\\.(ts|tsx)$": "jest-ts/dist/transformer.js"
  },
  globals: {
    "jest-ts": {
      typeCheck: true,
      tsconfigPath: "./tsconfig.test.json"
    }
  },
  moduleFileExtensions: ["ts", "tsx", "js"]
};

常见问题(FAQ)

Q1: 测试文件报错 “Cannot use import statement outside a module”

原因:Jest 未通过 jest-ts 转译 ES 模块语法,或模块系统配置不兼容。
解决方案

  1. 确认 jest.config.jspreset"jest-ts/jest-preset"(非本地路径)。
  2. 检查 tsconfig.jsonmodule 配置为 CommonJS(Jest 默认支持)。
  3. 执行 npm ls jest-ts 确认包已正确安装(无版本冲突)。

Q2: 开启 typeCheck: true 后,类型错误未被检测到

原因:TS 配置未包含测试文件,或 tsconfigPath 指向错误。
解决方案

  1. 确保 tsconfig.jsoninclude 包含测试目录:
    { "include": ["src/**/*", "__tests__/**/*"] }
  2. 若使用测试专用配置(如 tsconfig.test.json),确认 tsconfigPath 路径正确。

Q3: 缓存未刷新,修改代码后测试结果不变

原因:缓存基于代码内容和配置哈希,未检测到变更时复用旧缓存。
解决方案

  1. 手动删除缓存目录(默认 ./node_modules/.cache/jest-ts)。
  2. 版本更新时,jest-ts 会自动根据包版本刷新缓存。

Q4: 执行 npx jest-ts init 提示 “command not found”

原因jest-ts 未安装到项目依赖,或 npm 版本过低。
解决方案

  1. 先安装依赖:npm install jest-ts --save-dev
  2. 再执行初始化:npx jest-ts init

许可证

MIT