Using test hooks
Nightwatch provides the standard before
/after
and beforeEach
/afterEach
hooks to be used in the tests.
before, beforeEach, after, afterEach
The before
and after
will run before and after the execution of the test suite respectively, while beforeEach
and afterEach
are ran before and after each testcase (test step).
All methods have the Nightwatch instance passed as argument.
Example:
module.exports = {
before : function(browser) {
console.log('Setting up...');
},
after : function(browser) {
console.log('Closing down...');
},
beforeEach : function(browser) {
},
afterEach : function(browser) {
},
'step one' : function (browser) {
browser
// ...
},
'step two' : function (browser) {
browser
// ...
.end();
}
};
In the example above the sequence of method calls will be as follows: before(), beforeEach(), "step one", afterEach(), beforeEach(), "step two", afterEach(), after()
.
Asynchronous before[Each] and after[Each]
All the before[Each]
and after[Each]
methods can also perform asynchronous operations, in which case they will require the callback
passed as the second argument.
done
function must be called as the last step when the async operation completes. Not calling it will result in a timeout error.
Example with beforeEach & afterEach:
module.exports = {
beforeEach: function(browser, done) {
// performing an async operation
setTimeout(function() {
// finished async duties
done();
}, 100);
},
afterEach: function(browser, done) {
// performing an async operation
setTimeout(function() {
// finished async duties
done();
}, 200);
}
};
Controlling the done
invocation timeout
By default the done
invocation timeout is set to 10 seconds (2 seconds for unit tests). In some cases this might not be sufficient and to avoid a timeout error, you can increase this timeout by defining an asyncHookTimeout
property (in milliseconds) in your external globals file (see below for details on external globals).
For an example, refer to the provided globalsModule example.
Explicitly failing the test
Failing the test intentionally in a test hook can be achieved by calling done
with an Error
argument:
module.exports = {
afterEach: function(browser, done) {
// performing an async operation
performAsync(function(err) {
if (err) {
done(err);
return;
}
// ...
});
}
};
Global Test Hooks
The same set of test hooks as per test suite is also available globally, outside the scope of the test. Refer to the next section for details.