typescriptbeginner

Native Test Runner and Assert

Write tests using Node.js built-in test runner and assert module — no external dependencies needed.

typescript
import { describe, it, before, after, beforeEach } from 'node:test';
import assert from 'node:assert/strict';

// Function under test
function add(a: number, b: number): number {
  return a + b;
}

function divide(a: number, b: number): number {
  if (b === 0) throw new Error('Division by zero');
  return a / b;
}

function parseAge(input: string): number | null {
  const n = parseInt(input, 10);
  if (isNaN(n) || n < 0 || n > 150) return null;
  return n;
}

async function fetchData(id: number): Promise<{ id: number; name: string }> {
  if (id <= 0) throw new Error('Invalid ID');
  return { id, name: `User-${id}` };
}

// Tests
describe('add', () => {
  it('should add two positive numbers', () => {
    assert.equal(add(2, 3), 5);
  });

  it('should handle negative numbers', () => {
    assert.equal(add(-1, -2), -3);
  });

  it('should handle zero', () => {
    assert.equal(add(0, 0), 0);
  });
});

describe('divide', () => {
  it('should divide numbers', () => {
    assert.equal(divide(10, 2), 5);
  });

  it('should return float', () => {
    assert.equal(divide(1, 3), 1 / 3);
  });

  it('should throw on division by zero', () => {
    assert.throws(
      () => divide(10, 0),
      { message: 'Division by zero' }
    );
  });
});

describe('parseAge', () => {
  it('should parse valid age', () => {
    assert.equal(parseAge('25'), 25);
  });

  it('should return null for invalid', () => {
    assert.equal(parseAge('abc'), null);
  });

  it('should reject negative', () => {
    assert.equal(parseAge('-5'), null);
  });

  it('should reject too high', () => {
    assert.equal(parseAge('200'), null);
  });
});

describe('fetchData', () => {
  it('should return user data', async () => {
    const data = await fetchData(1);
    assert.deepEqual(data, { id: 1, name: 'User-1' });
  });

  it('should throw for invalid ID', async () => {
    await assert.rejects(
      () => fetchData(-1),
      { message: 'Invalid ID' }
    );
  });
});

describe('assert methods', () => {
  it('deep equality', () => {
    assert.deepEqual({ a: 1, b: [2, 3] }, { a: 1, b: [2, 3] });
  });

  it('not equal', () => {
    assert.notEqual(1, 2);
  });

  it('truthy/falsy', () => {
    assert.ok(true);
    assert.ok(1);
    assert.ok('non-empty');
  });

  it('match string', () => {
    assert.match('hello world', /world/);
  });

  it('doesNotMatch', () => {
    assert.doesNotMatch('hello', /world/);
  });
});

Use Cases

  • Unit testing without external packages
  • Quick test setup for Node.js projects
  • CI/CD test automation

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.