Fundamentals of Testing in TypeScript #3

April 2, 2021
Open playground

In the previous article, we created a specialized expect function that returns an object with assertions, but one of our assertion function's side effects is that as soon as one assertion fails, it throws an error, so other tests do not run. A testing framework exists to help the developer identify what is broken as soon as possible. We can ensure that we will provide more helpful error messages and by running all of our tests.

Let's create our own test function to encapsulate our automated tests and abstract them. Also, we want to ensure that we will run all the tests with more helpful error messages.

Our test function will accept a title of the test and a callback.

Because our test function can throw an error, we will wrap it in a try-catch statement. Inside the try block, we will call our callback, and if the callback throws an error, we will log it out.

To help a developer identify which functionality is broken, we will log the title. For better visibility, we are adding ✅ and ❌ emojis.

1const test = <T>(title: string, callback: () => T) => {
2 try {
3 callback()
4 console.log(`${title}`)
5 } catch (error) {
6 console.error(`${title}`)
7 console.error(error)
8 }
9}

Now let's encapsulate our assertion to a function and pass it as a callback to our test function.

1test('add function', () => expect(add(8, 16)).toBe(24))
2test('subtract function', () => expect(subtract(32, 16)).toBe(16))

Now, we can rerun our test file, but we need to look into the console instead of the tests tab. It is now clearly visible that the problem is inside our add function, not in the subtract.

1❌ add function
2Error: -8 is not equal to 24
3
4✅ subtract function