Introduction
Mocha is a JavaScript framework that runs on Node.js and makes asynchronous testing significantly easy and fun. Mocha tests run serially, allowing for flexible and accurate reporting while mapping uncaught exceptions to the correct test cases.
This blog will help you understand what Retrying Tests are in MochaJS and its implementation.
Retrying Tests
When a test fails, it is still possible to attempt it a certain number of times. Mocha has a retry feature that enables it to handle end-to-end tests such as Selenium and functional tests.
It is important to note that the retry feature is not recommended for unit tests.
Additionally, while providing the ability to re-run a failed test, the retry feature does not run the before or after hooks. However, it will re-run the corresponding afterEach and beforeEach hooks.
To help understand the above statements, consider the code below.
describe('retries', function() {
// this code will retry all the tests in this suite up to 2 times.
this.retries(2);
beforeEach(function() {
browser.get('http://www.google.com');
});
it('has to succeed on the 2nd try', function() {
// Specify that this test is to only retry up to 3 times
this.retries(3);
expect($('.foo').isDisplayed()).to.eventually.be.true;
});
});
Let us consider another example:
describe('retries', function() {
// this will retry all tests in this suite up to 4 times
this.retries(4);
beforeEach(function() {
browser.get('http://www.codingninjas.com');
});
it('should succeed on the 2nd try', function() {
// Specify this test to only retry up to 2 times
this.retries(2);
expect($('.foo').isDisplayed()).to.eventually.be.true;
});
});




