Search⌘ K
AI Features

Perform an Action Before and After Each Test

Explore how to use Jasmine hooks like beforeEach and afterEach to automate setup and cleanup tasks around your tests. This lesson helps you write cleaner, more efficient JavaScript unit tests by managing repetitive actions and keeping test environments clean.

In the previous lesson, we saw that there were clock install and uninstall actions that were done as part of the spec:

it('should return 7 for a date 7 days ago', () => {
    const clock = jasmine.clock();
    ... // test code skipped

    clock.uninstall();
});

That logic is not a part of the test. It’s also repeated verbatim for each test. We can do better.

Jasmine hooks

There are a few functions we can call and let Jasmine know that ...