Reputation: 597
I know mocha has global before and after, and each-test before and after, but what I would like is test-specific before and after. Something like SoapUI has.
For example, say that I have a test checking that the creation of a user works.
I want to remove the user, should it exist, from the database BEFORE the test. And I want the test to ensure that the user is removed AFTER the test. But I do not want to do this for EACH test, as only one test will actually create the user. Other tests will delete user/s, update user/s, fail to create an already existing user etc.
Is this possible, or do I have to include the setup and tear down code in the test? If so, how do I ensure that both the setup and tear down executes properly, independent of the test result?
Upvotes: 2
Views: 1866
Reputation: 151391
For tests where I need to have special setup and teardown code but that are not otherwise distinguishable from their siblings, I just put a describe
block with an empty title:
describe("SomeClass", () => {
describe("#someMethod", () => {
it("does something", () => {});
it("does something else", () => {});
describe("", () => {
// The before and after hooks apply only to the tests in
// this block.
before(() => {});
after(() => {});
it("does something more", () => {});
});
});
});
Is this possible, or do I have to include the setup and tear down code in the test? If so, how do I ensure that both the setup and tear down executes properly, independent of the test result?
You can put setup and tear down code in the test itself (i.e. inside an the callback you pass to it
). However, Mocha will treat any failure there as a failed test, period. It does not matter where in the callback passed to it
the failure occurs. Assertion libraries allow you to provide custom error messages which can help you figure out what exactly failed, but Mocha will see all failures in it
the same way: the test failed. If you want Mocha to treat failures in setup/teardown code differently from test failures, then you have to use the hooks as I've shown above.
Upvotes: 6