DEV Community

Cover image for Fundamentals of Testing in TypeScript #1
Lukas Polak
Lukas Polak

Posted on • Originally published at lukaspolak.com

Fundamentals of Testing in TypeScript #1

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.

export const add = (a: number, b: number): number => {
  return a - b
}
Enter fullscreen mode Exit fullscreen mode

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

let result = add(8, 16)
let expectedResult = 24
Enter fullscreen mode Exit fullscreen mode

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:

if (result !== expectedResult) {
  throw new Error(`${result} is not equal to ${expectedResult}`)
}
Enter fullscreen mode Exit fullscreen mode

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.

export const add = (a: number, b: number): number => {
  return a + b // Test will pass now 🔥
}
Enter fullscreen mode Exit fullscreen mode

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

export const subtract = (a: number, b: number): number => {
  return a - b
}
Enter fullscreen mode Exit fullscreen mode

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

// ...

result = subtract(32, 16)
expectedResult = 16

if (result !== expectedResult) {
  throw new Error(`${result} is not equal to ${expectedResult}`)
}
Enter fullscreen mode Exit fullscreen mode

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.


CodeSandbox playground:

Top comments (0)