4

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

1 Answer 1

9

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(...);
  });

});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I have another, similar question. My afterEach hook involves an async method that 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?
Mocha has built-in promise support, if you return one from either a test or one of the hooks, Mocha will wait until it gets resolved before continuing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.