Reputation:
I use mocha for some integration testing and have many test sets. Each set has initialization tests. When such tests fail, the rest of the set should not run at all, because if one fails then each will fail. The thing is that I can't avoid such initialization tests, because part of the code/environment is generated by some tool which does not guarantee any correct result.
Is it possible to implement this using mocha ?
Upvotes: 5
Views: 2488
Reputation: 4156
I found mocha-steps
which basically allow you to write a "chain" of it()
s (called step()
) and mocha will abort the suite if one of them breaks, thus avoiding the cascade of inevitable failures, and I found pull request 8 marks subsequent steps and subsuites as pending. So I can write:
describe("businessCode()", function() {
step("should be not null", function() {
assert(businessCode() != null)
});
step("should be a number", function() {
assert(typeof businessCode() === 'number');
});
step("should be greater than 10", function() {
assert(businessCode() > 10);
});
describe("thingThatCallsBusinessCode()", function() {
step("should be greater than 10", function() {
assert(thingThatCallsBusinessCode() != null);
});
});
});
If e.g. businessCode()
returns a boolean, only the should be a number
test will fail; the subsequent ones (and the subsuite will be marked as pending).
Upvotes: 1
Reputation: 151370
Using the BDD interface, the normal way to do this with Mocha is to put anything that sets up the testing environment into before
or beforeEach
:
describe("foo", function () {
describe("first", function () {
before(function () {
// Stuff to be performed before all tests in the current `describe`.
});
beforeEach(function () {
// Stuff to perform once per test, before the test.
});
it("blah", ...
// etc...
});
describe("second", function () {
before(function () {
// Stuff to be performed before all tests in the current `describe`.
});
beforeEach(function () {
// Stuff to perform once per test, before the test.
});
it("blah", ...
// etc...
});
});
If the before
or beforeEach
that a test depends on fails, then the test is not run. Other tests that don't depend on it will still run. So in the example above if the callback passed to before
in the describe
named first
fails, the tests in the describe
named second
won't be affected at all and will run, provided that their own before
and beforeEach
callbacks don't fail.
Other than this, Mocha is designed to run tests that are independent from each other. So if one it
fails, then the others are still run.
Upvotes: 2