Reputation: 391
When using Jasmine, is there a difference between adding a matcher in a beforeAll
block vs a beforeEach
block?
As far as I can tell, it works both ways. However, every documentation/tutorial I find online uses beforeEach
. Is this simply because Jasmine's built-in beforeAll
block is a relatively new feature, or is it avoided due to a potential pitfall when running the tests?
Using beforeAll
makes more sense to me (why add the same matcher more than once?), but I'd like to make sure that I'm not exposing my tests to any problems.
Upvotes: 4
Views: 284
Reputation: 1224
There are two differences - 1) the execution order, and 2) the scope in which the change is persistent. I've spent many hours testing in Jasmine at work and the differences between beforeAll
and beforeEach
have always behaved as they should (well, except one bug I helped them fix). The only reason I've found to use beforeEach
instead of beforeAll
is to avoid test pollution. This isn't an issue for custom matchers, so it should be just fine to go ahead and use beforeAll
.
Execution order - in any given describe
block, order is as follows:
beforeAll
beforeEach
it
or describe
block (including their setups and teardowns)afterEach
it
or describe
block, repeat the last three stepsafterAll
I've confirmed this through testing and sources like this.
Scope - Any added variables, properties on the this keyword, spies, or custom matchers (as mentioned), will be persistent and accessible in the given block, throughout the block (including in nested blocks), as soon as the code that adds them has been executed. For example, if I set this.foo
in the beforeAll
of a describe
, it can be accessed in that describe
's beforeEach
, afterEach
, afterAll
, and it
and describe
blocks. As soon as I leave the describe block, this.foo
will no longer be accessible.
Upvotes: 2