DEV Community

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

Posted on • Originally published at lukaspolak.com

Fundamentals of Testing in TypeScript #2

In the previous article we written our first testing assertion.

In this article we will abstract our assertion, which will help us with readability and avoiding unnecessary code duplication.

Our testing assertion is imperative. It would be appropriate to write a thin layer of abstraction to make it more universal. So first, we will write a simple function to encapsulate our assertion.

Our function expect will accept the value parameter. It will return an object with the assertion toBe, which accepts expected as a parameter.
Inner implementation of the toBe function will be the same as our previous article's assertion.

const expect = <T>(value: T) => {
  return {
    toBe(expected: T) {
      if (value !== expected) {
        throw new Error(`${value} is not equal to ${expected}`)
      }
    },
  }
}
Enter fullscreen mode Exit fullscreen mode

Now we can remove code duplication and make our code more universal.

//...

expect(add(8, 16)).toBe(24)

expect(subtract(32, 16)).toBe(16)
Enter fullscreen mode Exit fullscreen mode

If we rerun our tests, we will get the same error message. At the most basic level, our function takes a value, and then it returns an object with specialized assertion. Currently, we have only a toBe assertion. Still, we can easily create a toEqual for deep equality check, or toBeLessThan and toBeGreaterThan for comparing numbers.

Top comments (0)