Jasmine beforeEach() Function
The Jasmine
beforeEach() function allows you to
execute some code before the spec in the
it() block.
In Neil Gaiman's fantasy novel Stardust, there is a wall which divides England and the magical kingdom of Stormhold. Our hero of the story Tristan has to enter Stormhold to go get a fallen star.
We create a test suite where the variable
tristan is initialized to
'England'. We expect the variable
tristan to take the value
'Stormhold' inside the
setTimeout() function after 1.5 seconds
describe('Tristan Thorn', function() {
var tristan = 'England';
setTimeout(function() {
tristan = 'Stormhold';
}, 1500);
it('is in Stormhold', function() {
expect(tristan).toEqual('Stormhold');
});
});
The test fails because the it() block is
executed before completion of the
setTimeout() operation, and the
tristan variable still holds the initial
value 'England'.
Async operations (as in the example above) goes inside the
beforeEach() function, to which the
done() function is passed as an argument
causing Jasmine to wait until it is called before executing the spec
in the it() block. The test suite can now
be rewritten as
describe('Tristan Thorn', function() {
var tristan = 'England';
beforeEach(function(done) {
setTimeout(function() {
tristan = 'Stormhold';
done();
}, 1500);
});
it('is in Stormhold', function() {
expect(tristan).toEqual('Stormhold');
});
});
This time, the spec passes. On running the spec configured in Grunt, the output to the terminal looks like
Notes
-
More details on the
done()function can be found under the following link - http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support.