I have a simple example of two tests (A,B) where B depends on A being run.
If I am using Mocha, I can nest test B within A:
describe.only( 'AB:', function() {
describe( 'A', function() {
it( 'A1', function() {
assert.equal( 1, 2 );
} );
describe( 'B', function() {
it( 'B1', function() {
assert.equal( 1, 1 );
} );
} );
} );
} );
But both A and B are run even if A fails.
How is this any different than not using nesting?
describe.only( 'AB:', function() {
describe( 'A&B', function() {
it( 'A1', function() {
assert.equal( 1, 2 );
} );
it( 'B1', function() {
assert.equal( 1, 1 );
} );
} );
} );
Is there any way to skip B if A fails?
The easiest way to achieve this is to use mocha-steps:
describe('my smoke test', function() {
step('login', function() {
});
step('buy an item', function() {
throw new Error('failed');
});
step('check my balance', function() {
});
xstep('temporarily ignored', function() {
});
});
Full blog post here.
Ok, there are two questions, so I'll try to answer both.
Is there any way to skip B if A fails?
Generally you should write tests that are not dependent on each other.
Sometimes tests depend on having certain setup or state before they're able to be run properly though, in which case it's best to do the setup in a before()
or beforeEach()
block. If either of these blocks fail, the tests after them are not run. Thus you can throw an error in those blocks, when your build up is in a way that you know none of the tests inside that describe block are not going to work.
describe.only('AB:', function() {
var numberUnderTest = 0;
describe('A&B', function() {
it('A1', function() {
assert.equal(1, 1 * numberUnderTest);
});
describe('B', function() {
before(function() {
if (numberUnderTest === 0) {
throw 'cannot divide by zero';
}
});
it('B1', function() {
assert.equal(1, 1 / numberUnderTest);
});
});
});
});
If I am using Mocha, I can nest test B within A
[...]
How is this any different than not using nesting?
Nesting B inside a describe block allows you to use a different setup for B1 than for A1, while still inheriting some of A's setup.
describe('A', function() {
var numberUnderTest;
var anotherNumber;
beforeEach(function() {
numberUnderTest = 1;
anotherNumber = 0;
});
it('A1'), function() {
assert.equal(0, anotherNumber * numberUnderTest);
});
describe('B', function() {
before(function() {
anotherNumber = 1;
});
it('B1', function() {
assert.equal(1, anotherNumber / numberUnderTest);
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With