Akabutz
Akabutz

Reputation: 41

How to run 'After' code on Mocha only on specific tests?

Edit: This question was answered, but I have another, similar question which I didn't want to open a new thread for.

I'm using Mocha and Chai to test my project.

As part of my code, I create a new user and save him in our DB (so the test user can perform various methods on our app).

Generally, after every test I would like to run a code block that deletes the user from the DB, which I did using the "AfterEach" hook.

My problem is that I have 1 test (might be more in the future) which doesn't create a user (e.g, 'try to login without signing up'), so my AfterEach code receives an error (can't delete something that doesn't exist).

Does Mocha supply a way to disable the 'AfterEach' on some tests? Or some other solution to my problem.

Edit: Added question: my AfterEach hook involves an async method which returns a promise. On the Mocha documentation I only saw an example for async hooks that work with callbacks. How am I supposed to use an afterEach hook that returns a promise

Upvotes: 4

Views: 4942

Answers (1)

robertklep
robertklep

Reputation: 203359

You can nest describe blocks, so you can group user interaction tests and also group the "with user" and "without user" tests:

describe('user interaction', () => {

  describe('with user in database', () => {
    // these will run only for the tests in this `describe` block:
    beforeEach(() => createUser(...));
    afterEach (() => deleteUser(...));

    it(...);
  });

  describe('without user in database', () => {
    it(...);
  });

});

Upvotes: 9

Related Questions