|
| 1 | +By default, [Mocha's BDD interface adds a global `afterEach()` function](https://mochajs.org/#bdd). |
| 2 | +You can call `afterEach()` with a function, and Mocha will execute that function after every test in the suite. |
| 3 | +You should use `afterEach()` to clean up any persistent state your test created, like entries saved in your database or calling `sinon.restore()`. |
| 4 | + |
| 5 | +```javascript |
| 6 | +afterEach(function() { |
| 7 | + console.log('Running afterEach!'); |
| 8 | +}); |
| 9 | + |
| 10 | +// Prints "Running afterEach!" after "test1" |
| 11 | +it('test1', function() { |
| 12 | + console.log('test1'); |
| 13 | +}); |
| 14 | +// Prints "Running afterEach!" after "test2" |
| 15 | +it('test2', function() { |
| 16 | + console.log('test2'); |
| 17 | +}); |
| 18 | +``` |
| 19 | + |
| 20 | +`afterEach()` is like [`beforeEach()`](/tutorials/mocha/beforeeach), but runs after every test rather than before. |
| 21 | + |
| 22 | +## With `describe()` |
| 23 | + |
| 24 | +`describe()` lets you scope `afterEach()` hooks. |
| 25 | +If you define a `afterEach()` in a `describe()`, Mocha will not run that `afterEach()` on any tests outside of that `describe()`. |
| 26 | + |
| 27 | +```javascript |
| 28 | +afterEach(function() { |
| 29 | + console.log('Running global afterEach!'); |
| 30 | +}); |
| 31 | + |
| 32 | +describe('my test suite', function() { |
| 33 | + afterEach(function() { |
| 34 | + console.log('Running my test suite afterEach!'); |
| 35 | + }); |
| 36 | + |
| 37 | + // Prints both "Running afterEach!" and "Running my test suite afterEach!" |
| 38 | + it('test1', function() {}); |
| 39 | + // Prints both "Running afterEach!" and "Running my test suite afterEach!" |
| 40 | + it('test2', function() {}); |
| 41 | +}); |
| 42 | + |
| 43 | +// Only prints "Running global afterEach!" |
| 44 | +it('test3', function() {}); |
| 45 | +``` |
| 46 | + |
| 47 | +So a global `afterEach()` will run after every test, even tests within a `describe()`. |
| 48 | +But a `afterEach()` hook within a `describe()` will not run on any test outside of that `describe()`. |
| 49 | + |
| 50 | +## Skipped Tests |
| 51 | + |
| 52 | +Mocha will **not** run `afterEach()` if there are no tests. |
| 53 | +For example, if you [run a single Mocha test](./run-single-test) using `.only()`, Mocha will not execute the `afterEach()` hook in the following test file. |
| 54 | + |
| 55 | +```javascript |
| 56 | +describe('my test suite', function() { |
| 57 | + afterEach(function() { |
| 58 | + console.log('Running my test suite afterEach!'); |
| 59 | + }); |
| 60 | + |
| 61 | + it('test1', function() {}); |
| 62 | + it('test2', function() {}); |
| 63 | +}); |
| 64 | + |
| 65 | +// Because of `.only()`, Node will **not** print |
| 66 | +// "Running my test suite afterEach!" |
| 67 | +it.only('test3', function() {}); |
| 68 | +``` |
0 commit comments