Fundamentals of Testing in TypeScript #2

April 12, 2021

Open playground

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.

index.ts
const expect = <T>(value: T) => {
return {
toBe(expected: T) {
if (value !== expected) {
throw new Error(`${value} is not equal to ${expected}`)
}
},
}
}

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

index.ts
//...
expect(add(8, 16)).toBe(24)
expect(subtract(32, 16)).toBe(16)

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.

See you in the following article, where we create a custom test function that would be more helpful to a developer.

Share this post on Twitter