beforeEach()

To help a test suite DRY up any duplicated setup and teardown code, Jasmine provides the global beforeEach and afterEach functions. As the name implies, the beforeEach function is called once before each spec in the describe in which it is called, and the afterEach function is called once after each spec. Here is the same set of specs written a little differently. The variable under test is defined at the top-level scope -- the describe block -- and initialization code is moved into a beforeEach function. The afterEach function resets the variable before continuing.

The beforeEach() method will help us out in sharing global instances for example:

describe('CalculatorService', () => {
    let calculator: CalculatorService,
    loggerSpy: LoggerService;

    beforeEach(() => {
        console.log('Calling beforeEach');
        loggerSpy = jasmine.createSpyObj('LoggerService', ['log']); // Call the spy
        calculator = new CalculatorService(loggerSpy); // Call the calculator
    });
    
    it('should add two numbers', () => {
        console.log('Add test');
        const result = calculator.add(2, 2);
        expect(result).toBe(4);
        expect(loggerSpy.log).toHaveBeenCalledTimes(1);
    });
    it('should substract two numbers', () => {
        console.log('Subtract test');
        const result = calculator.subtract(2, 2);
        expect(result).toBe(0, 'Wrong operation, please check it out');
        expect(loggerSpy.log).toHaveBeenCalledTimes(1);
    });
});

Last updated