Testing And Benchmarking in TypeScript
Here’s an idiomatic TypeScript example demonstrating unit testing and benchmarking:
// math.ts
export function intMin(a: number, b: number): number {
return a < b ? a : b;
}
// math.test.ts
import { intMin } from './math';
describe('intMin', () => {
it('should return the minimum of two integers', () => {
expect(intMin(2, -2)).toBe(-2);
});
it.each([
[0, 1, 0],
[1, 0, 0],
[2, -2, -2],
[0, -1, -1],
[-1, 0, -1],
])('should return %i for intMin(%i, %i)', (a, b, expected) => {
expect(intMin(a, b)).toBe(expected);
});
});
// math.bench.ts
import { intMin } from './math';
import { performance } from 'perf_hooks';
function benchmarkIntMin(iterations: number): number {
const start = performance.now();
for (let i = 0; i < iterations; i++) {
intMin(1, 2);
}
const end = performance.now();
return end - start;
}
console.log(`Benchmark: ${benchmarkIntMin(1000000)} ms`);
This example demonstrates unit testing and benchmarking in TypeScript. Let’s break it down:
We define a simple
intMin
function inmath.ts
that returns the minimum of two numbers.In
math.test.ts
, we use Jest (a popular testing framework for TypeScript) to write unit tests:- The first test checks a basic case.
- The second test uses
it.each
to run multiple test cases in a table-driven style.
In
math.bench.ts
, we create a simple benchmark function that measures the time taken to runintMin
a specified number of times.
To run the tests and benchmark:
Install the necessary dependencies:
npm install --save-dev typescript ts-jest @types/jest
Configure Jest in your
package.json
:{ "jest": { "preset": "ts-jest", "testEnvironment": "node" } }
Run the tests:
npx jest
Run the benchmark:
ts-node math.bench.ts
This example showcases TypeScript’s strong typing (e.g., function parameters and return types) and uses modern testing practices like table-driven tests. The benchmark demonstrates how to measure performance, although for more complex scenarios, you might want to use a dedicated benchmarking library.
Remember that TypeScript is transpiled to JavaScript, so you don’t compile it directly to a binary like in Go. Instead, you typically run it through Node.js or bundle it for browser use.