An all-in-one test framework supporting TypeScript out-of-box.
- 100% compatible with Jest. Use
typed-jest
just like you would usejest
. - Out-of-the-box TypeScript support.
- All in one. The best practice to use jest in TypeScript (CJS) project.
- No implicit globals.
- Sensible defaults adhering to best practices. Most projects work seamlessly with zero configuration.
- Integrated supertest in it.
This is an all-in-one test framework designed for legacy CommonJS TypesScript project, supporting experimentalDecorators
and emitDecoratorMetadata
. For modern ESM project, you should consider to use Vitest.
- Uninstall
jest
,@types/jest
, andts-jest
if they are already installed in your project.
pnpm remove jest @types/jest ts-jest
- Install
typed-jest
.
pnpm add -D typed-jest
- Create an
app.ts
file.
import fs from "node:fs";
import express, { type Express } from "express";
const json = fs.readFileSync("package.json", "utf-8");
const app: Express = express();
app.get("/pkg", function (_req, res) {
console.log("package.json", json);
res.status(200).json(JSON.parse(json));
});
export default app;
- Create an
app.spec.ts
file.
import { afterEach, beforeEach, describe, expect, it, jest } from "typed-jest";
import supertest from "typed-jest/supertest";
import app from "./app";
jest.mock("node:fs", () => ({
readFileSync: () => JSON.stringify({ foo: "bar" }),
}));
describe("app", () => {
beforeEach(() => {
console.log("========beforeEach running========");
});
afterEach(() => {
console.log("========afterEach running========");
});
it("should be 2", () => {
expect(1 + 1).toBe(2);
});
it("should success", async () => {
const response = await supertest(app).get("/pkg");
expect(response.status).toEqual(200);
expect(response.body).toStrictEqual({ foo: "bar" });
});
});
- Run
pnpm jest
to execute tests.
Note: For the projects using
npm
as its package manager, please usenpx typed-jest
instead.
- Add more CLI configurations after the
pnpm jest
command. For example, runpnpm jest --coverage
to collect test coverage. Runpnpm jest -h
for more CLI options information. - Add a
jest.config.js
file in the root of your project. Consult the official Jest documentation for more information.
If you don't include CLI options when running pnpm jest
, we will append some sensible defaults:
--transform='{"^.+\\\\.tsx?$":"ts-jest"}'
: This option transforms TypeScript files, so you can support TypeScript projects without additional configurations or installations.--passWithNoTests
: This option prevents the CLI from producing errors if no tests are found. You can override this default bypnpm jest --passWithNoTests=false
.--collectCoverageFrom='**/src/**/*.{js,mjs,cjs,jsx,ts,mts,cts,tsx}'
: This option specifies the location for collecting test coverage. Override it as needed:pnpm jest --collectCoverageFrom='**/lib/**/*.js'
MIT