afterEach(fn, timeout)

Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing.

Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.

This is often useful if you want to clean up some temporary state that is created by each test.

For example:

const globalDatabase = makeGlobalDatabase(); function cleanUpDatabase(db) { db.cleanUp(); } afterEach(() => { cleanUpDatabase(globalDatabase); }); test('can find things', () => { return globalDatabase.find('thing', {}, results => { expect(results.length).toBeGreaterThan(0); }); }); test('can insert a thing', () => { return globalDatabase.insert('thing', makeThing(), response => { expect(response.success).toBeTruthy(); }); });

Here the afterEach ensures that cleanUpDatabase is called after each test runs.

If afterEach is inside a describe block, it only runs after the tests that are inside this describe block.

If you want to run some cleanup just once, after all of the tests run, use afterAll instead.