Mocha is a feature-rich JavaScript test framework for Node.js.
Mocha provides several built-in hooks that can be used to set up preconditions and clean up after your tests. The four most commonly used hooks are: before()
, after()
, beforeEach()
, and afterEach()
.
before(name, fn)
name
: Optional string for descriptionfn
: Function to run once before the first test caseafter(name, fn)
name
: Optional string for descriptionfn
: Function to run once after the last test casebeforeEach(name, fn)
name
: Optional string for descriptionfn
: Function to run before each test caseafterEach(name, fn)
name
: Optional string for descriptionfn
: Function to run after each test caseAll hooks may also be sync or async.
Mocha also provides root hooks that run before or after every test in every file. Read more about them here.
The hooks run in the order:
before()
hooks run (once)beforeEach()
hooks or testsafterEach()
hooksafter()
hooks (once)describe('hooks', function () {before('optional description', function () {// runs once before the first test in this block});after('optional description', function () {// runs once after the last test in this block});beforeEach('optional description', function () {// runs before each test in this block});afterEach('optional description', function () {// runs after each test in this block});// example test casesit('test case 1', function () {// ...});// Test case 2it('test case 2', function () {// ...});});