Global `beforeEach` in jasmine?

JavascriptUnit TestingJasmine

Javascript Problem Overview


I'm using Jasmine to write tests.

I have several test files, each file has a beforeEach, but they are exactly the same.

How do I provide a global beforeEach for them?

Javascript Solutions


Solution 1 - Javascript

x1a4's answer confused me. This may be more clear:

When you declare a beforeEach function outside all describe blocks, it will trigger before each test (so before each it). It does not matter if you declare the beforeEach before or after your describe blocks.

You can include this in any specfile included in your test run—including in a file all on its own, hence the concept of a spec helper file that might contain just your global beforeEach declaration.

It's not mentioned in the documentation.

// Example: 

beforeEach(function() {
    localStorage.clear();
});

describe('My tests', function() {
    describe('Test localstorage', function() {

        it('Adds an item to localStorage', function() {
            localStorage.setItem('foo', 'bar');
            expect(localStorage.getItem('foo')).toBe('bar');
        });

        it('Is now empty because our beforeEach cleared localStorage', function() {
            expect(localStorage.getItem('foo')).toBe(null);
        });

    });
});

Solution 2 - Javascript

You can put it in your spec_helper.js file and it should work fine.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFreewindView Question on Stackoverflow
Solution 1 - JavascriptBlaiseView Answer on Stackoverflow
Solution 2 - Javascriptx1a4View Answer on Stackoverflow