Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

before hook before all test cases in Mocha

I have a "before" hook that I want to run before all test cases(files), the ideal situation would be run it once and only once no matter how many test cases and which test case I run.

Now what I do is putting that "before" hook in a separate file, and do "require("../beforeAll.js")" in the beginning of every test file,

//beforeAll.js
before('description', function(done) {
    //do something
    done()
}


//all test files
require('../beforeAll.js')
//test 
//......

which I think will run the "before" hook every time a test file runs, but I don't know better way to do it. However, when I run all the test cases, the "before" hook actually runs only once.

So my question are, why the "before" hook runs only once? What is the best way to do it in this scenario(only run once)?

like image 824
Keming Avatar asked Dec 13 '22 20:12

Keming


1 Answers

According to MochaJS's documentation on hooks:

before(function() {}) runs before all tests in the block.
beforeEach(function() {}) runs before each test in the block.

If you want to run a singular function at the start of your tests, use before().
If you want to run a function before each of your tests, use beforeEach().

When you make use of require(), you are essentially 'including' that logic in the current test, as though you are copy-pasting the required file. Considering you make use of before(), it runs in the first test. When it comes time to the second test, it sees that before() has already executed, so it does not get executed again.

Hope this helps! :)

like image 62
Obsidian Age Avatar answered Dec 20 '22 22:12

Obsidian Age