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.

1export const add = (a: number, b: number): number => {
2 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.

1let result = add(8, 16)
2let 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:

1if (result !== expectedResult) {
2 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.

1export const add = (a: number, b: number): number => {
2 return a + b // Test will pass now 🔥

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

1export const subtract = (a: number, b: number): number => {
2 return a - b

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

1// ...
3result = subtract(32, 16)
4expectedResult = 16
6if (result !== expectedResult) {
7 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