Fundamentals of Testing in TypeScript #1

March 31, 2021

Open playground

First, we need to get a fundamental understanding of what an automated test is in TypeScript.

A test is a code that throws an error when the actual result of something does not match the expected result.

The tests can be more complicated when dealing with code that is dependent on the state (component needs to be in the document before you can fire a browser event, or data needs to be fetched before interacting with the component). Nevertheless, it is relatively easy to test pure functions.

Pure function will always return the same output for a given input and not change the state around it.

We have a bug inside a sum function. Instead of adding, it subtracts. We can quickly fix that, but we want to write an automated test to make sure that we will not reencounter this bug.

index.ts
export const add = (a: number, b: number): number => {
return a - b
}

We are expecting that the result constant will be 24, so create a new variable expectedResult with that value for better readability.

index.ts
let result = add(8, 16)
let expectedResult = 24

We can say if the result is not equal to the expectedResult throw an error that says result does not match an expectedResult with some hints:

index.tsx
if (result !== expectedResult) {
throw new Error(`${result} is not equal to ${expectedResult}`)
}

The thrown error will be: -8 is not equal to 24

If we replace the minus symbol with a plus inside the add function, our test passes without throwing any error. This is the most fundamental part of a test.

index.ts
export const add = (a: number, b: number): number => {
return a + b // Test will pass now 🔥
}

To get more familiarity with this, we can add another function subtract.

index.ts
export const subtract = (a: number, b: number): number => {
return a - b
}

For simplicity, we will copy-paste our conditional assertion.

index.ts
// ...
result = subtract(32, 16)
expectedResult = 16
if (result !== expectedResult) {
throw new Error(`${result} is not equal to ${expectedResult}`)
}

This time, our tests are passing without an error.

Errors should be as helpful as possible to quickly identify where the problem is and fix it.

See you in the following article, where we abstract our test assertion.

Share this post on Twitter