Perform an Action Before and After Each Test

Learn to use Jasmine hooks to perform actions before or after tests.

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 we’d like it to perform a certain action before each test or after each test. Let’s see how that might look like in the code playground below. Notice the spec/days-ago.spec.mjs file.

Get hands-on with 1200+ tech skills courses.