Fundamentals of Testing in TypeScript #3

lukaspolak

Lukas Polak

Posted on April 3, 2021

Fundamentals of Testing in TypeScript #3

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.

const test = <T>(title: string, callback: () => T) => {
  try {
    callback()
    console.log(`✅ ${title}`)
  } catch (error) {
    console.error(`❌ ${title}`)
    console.error(error)
  }
}
Enter fullscreen mode Exit fullscreen mode

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

test('add function', () => expect(add(8, 16)).toBe(24))
test('subtract function', () => expect(subtract(32, 16)).toBe(16))
Enter fullscreen mode Exit fullscreen mode

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.

❌ add function
Error: -8 is not equal to 24

✅ subtract function
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
lukaspolak
Lukas Polak

Posted on April 3, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related