-
Notifications
You must be signed in to change notification settings - Fork 0
Mocha
Mocha is a framework used to structure tests.
The it
function declares a test in Mocha. It is basically just a name (describing what the expected result is) and a function with the actual test code, eg.:
it('should calculate the sum of 2 numbers', function() {
// ...
});
Describe blocks group a set of tests. Describe blocks can be nested and add more context to a subset of tests. They have the same signature as it
, eg:
describe('The calculator', function() {
describe('The memory section', function() {
describe('The MR button', function() {
it('should output the currently saved value', function() {
// ...
});
it('should not clear the memory', function() {
// ...
});
});
});
});
Describe blocks also allow you to add setup and teardown code for tests. Setup can be done with either before
(run once) or beforeEach
(run before each tests). Subsequently teardown code can be added with the after
and afterEach
methods. Each setup/teardown block is executed on the describe level and on all sub-levels.
Eg. the following code...
describe('The outer scope', function() {
before(function() {
console.log('outer before');
});
beforeEach(function() {
console.log('outer before each');
});
it('should run in the outer scope', function() {
console.log('outer test 1');
});
it('should also run in the outer scope', function() {
console.log('outer test 2');
});
describe('The inner scope', function() {
before(function() {
console.log('inner before');
});
beforeEach(function() {
console.log('inner before each');
});
it('should run in the inner scope', function() {
console.log('inner test 1');
});
it('should also run in the inner scope', function() {
console.log('inner test 2');
});
afterEach(function() {
console.log('inner after each');
});
after(function() {
console.log('inner after');
});
});
afterEach(function() {
console.log('outer after each');
});
after(function() {
console.log('outer after');
});
});
... outputs the following in the console:
outer before
outer before each
outer test 1
outer after each
outer before each
outer test 2
outer after each
inner before
outer before each
inner before each
inner test 1
inner after each
outer after each
outer before each
inner before each
inner test 2
inner after each
outer after each
inner after
outer after
When working on a more complex test it may take too long to run all tests again to see just what the one test is doing. In that case you can write it.only
instead of it
and all other tests will be ignored. Note that only the last test marked with it.only
will be executed.
It's also possible to skip certain tests (eg. because they are temporarily failing for a know reason which cannot be fixed). This can be done with it.skip
or just xit
.