I ran into a problem recently that I can't explain. I have alot of code in these tests so I'm going to do my best to capture the idea here
I have tests that look like:
describe('main page', function() { beforeEach(function(done){ addUserToMongoDb(done); // #1 }); afterEach(function(done) { removeUserFromMongoDb(done); }); context('login', function() { it('should log the user in', function() { logUserIn(user_email); // #2 - This line requires the user from the beforeEach }); }); context('preferences', function() { before(function(done) { //#3 logUserInBeforeTest(user_email); }); it('should show the preferences', function() { doCheckPreferences(); // #4 }); }); });
The problem is, the beforeEach by #1
runs fine. I can see it happening on the DB and the tests in #2
pass.
However, the tests in the preferences context at #4
fail because it cant find the user to log them in at #3
.
It seems that the context before
is executed before the describe beforeEach
, which causes them to fail. If I move logUserIn
into the it
block it works fine.
What could cause this?
However, the order in which Mocha executes the hooks makes complete sense: a before hook is meant to set the stage for a group of tests, whereas a beforeEach test is for each individual tests.
Before is before the whole block, beforeEach is before each test. – Steven Scott. Sep 18, 2015 at 21:35.
The difference is beforeEach()/afterEach() automatically run before and after each tests, which 1. removes the explicit calls from the tests themselves, and 2. invites inexperienced users to share state between tests. Tests should be explicit, and tests should never share state.
JasmineJS - beforeEach() Using these two functionalities, we can execute some pieces of code before and after execution of each spec. This functionality is very useful for running the common code in the application.
While this answer just shows the documentation notes again, and had some comments to try to help show the difference, the answer below by @tomasz-wszelaki should be refered to.
Mocha's test runner explains this functionality the best in the Hooks section of the Mocha Test Runner.
From the Hooks section:
describe('hooks', function() { before(function() { // runs before all tests in this file regardless where this line is defined. }); after(function() { // runs after all tests in this file }); beforeEach(function() { // runs before each test in this block }); afterEach(function() { // runs after each test in this block }); // test cases });
You can nest these routines within other describe blocks which can also have before/beforeEach routines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With