← Back to TypeScript Course | Chapter 24: Testing TypeScript | Lesson 1 of 6

Jest with TypeScript

Jest is a JavaScript testing framework that can be used with TypeScript through a TypeScript-aware transformer or compiler setup. Tests should verify behavior while TypeScript types help make test code itself safer.

A Simple Jest Test

A basic Jest test in a TypeScript project uses the same describe/it/expect API as plain JavaScript, but ts-jest (or Babel's TypeScript preset) compiles the .ts test file before Jest runs it, catching type errors in your tests themselves.

Example: A Simple Jest Test

typescript
// sum.test.ts
function sum(a: number, b: number) { return a + b; }
// test("adds numbers", () => { expect(sum(1, 2)).toBe(3); });
console.log(sum(1, 2));

Testing Typed Functions

Testing a typed function lets Jest's type checker flag a test that calls the function with wrong argument types before the test even runs, catching a class of bugs that plain JavaScript tests can't.

Example: Testing Typed Functions

typescript
function double(x: number): number { return x * 2; }
// test("doubles a number", () => { expect(double(5)).toBe(10); });
// double("5") would be a compile-time error, caught before the test runs
console.log(double(5));

Testing Async Functions

Testing async functions requires await-ing the call inside the test body (or returning the promise), and TypeScript will infer the resolved type so expect() assertions get type-checked against the real return shape.

Example: Testing Async Functions

typescript
async function fetchValue(): Promise<number> { return 42; }
// test("resolves with 42", async () => { expect(await fetchValue()).toBe(42); });
fetchValue().then(console.log);

Testing Errors

Testing that a function throws uses expect(() => fn()).toThrow(), wrapping the call in an arrow function so Jest can catch the thrown error itself rather than the test crashing before the assertion runs.

Example: Testing Errors

typescript
function mustBePositive(n: number): number {
  if (n < 0) throw new Error("must be positive");
  return n;
}
// test("throws on negative", () => { expect(() => mustBePositive(-1)).toThrow(); });
try { mustBePositive(-1); } catch (e) { console.log("threw as expected"); }

Typed Test Data

Typed test data — building fixture objects that satisfy an interface — catches a broken fixture at compile time if the shape it's testing against ever changes, instead of failing confusingly at runtime.

Example: Typed Test Data

typescript
interface User { id: number; name: string; }
const fixture: User = { id: 1, name: "Test User" };
// test("fixture matches User shape", () => { expect(fixture.name).toBe("Test User"); });
console.log(fixture);
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.