Lesson Sunday

In the last lesson, we wrote six tests for a triangle tracker application. In each test, we needed to instantiate a Triangle object. These Triangle objects were all different, but what would happen if we needed to instantiate the same Triangle object for many tests?

This is a very common use case because we might want to instantiate the same object in different specs so you can test it in different ways. Fortunately, testing frameworks like Jest account for this by having additional methods for setup and teardown between tests. Setup is commonly used for instantiating variables and objects. Teardown is used for reinitializing objects or any variables that don't automatically fall out of scope between tests.

We can use beforeEach() blocks for setup and afterEach() blocks for teardown.

Let's imagine that we have a triangle that we want to reuse for multiple tests.

If this is the case, we'd use beforeEach() to DRY up the code. Here's an example:

__tests__/triangle.test.js
...
describe('Triangle', () => {
  let reusableTriangle;

  beforeEach(() => {
    reusableTriangle = new Triangle(5, 5, 5);
  });

  test('should show how beforeEach() works', () => {
    console.log(reusableTriangle);
  });
});

Here we declare reusableTriangle in the top-level scope. The beforeEach() function then assigns an instantiated object to the reusableTriangle variable. This object will be made available to each spec inside the suite. Now we don't need to define our reusableTriangle in each spec, which makes our code DRYer. Note that the example above isn't very helpful for the triangle code we just completed. This is because we need to instantiate different triangles for each test.

If we run our tests, we'll see that the value of the console.log() is printed to the terminal: Triangle { side1: 5, side2: 5, side3: 5 }. It may come as a bit of a surprise that console.log() prints to the terminal, but that is built-in functionality that Node provides. The benefits of console.log() aren't limited to the browser!

There's also an afterEach() function as well. This function is particularly useful if you need to perform some kind of teardown after each spec. For instance, if state from one spec somehow ends up in another spec, it could result in a failed spec or other unexpected behavior. Check the documentation on setup and teardown for more information.

Lesson 29 of 43
Last updated more than 3 months ago.