Skip to content

Instantly share code, notes, and snippets.

@iainsproat
Last active March 3, 2023 20:34
Show Gist options
  • Save iainsproat/10468584df9e64aaa0dfb9038b39f8c1 to your computer and use it in GitHub Desktop.
Save iainsproat/10468584df9e64aaa0dfb9038b39f8c1 to your computer and use it in GitHub Desktop.
Understanding mocha's nested before and after hooks
'use strict';
describe('mocha before and after hooks', function () {
before(() => console.log('*** top-level before()'))
beforeEach(() => console.log('*** top-level beforeEach()'))
after(() => console.log('*** top-level after()'))
afterEach(() => console.log('*** top-level afterEach()'))
describe('nesting', function () {
before(() => console.log('*** nested before()'))
beforeEach(() => console.log('*** nested beforeEach()'))
after(() => console.log('*** nested after()'))
afterEach(() => console.log('*** nested afterEach()'))
it('is a nested spec 1', () => console.log('nested spec 1'))
it('is a nested spec 2', () => console.log('nested spec 2'))
})
})
// *** top-level before()
// *** nested before()
// *** top-level beforeEach()
// *** nested beforeEach()
// nested spec 1
// *** nested afterEach()
// *** top-level afterEach()
// *** top-level beforeEach()
// *** nested beforeEach()
// nested spec 2
// *** nested afterEach()
// *** top-level afterEach()
// *** nested after()
// *** top-level after()
@iainsproat
Copy link
Author

Inspired by https://gist.github.com/harto/c97d2fc9d0bfaf20706eb2acbf48c908 with added after and afterEach

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment