I'm using mocha via the command line to test a web application. There is a function that exists solely to assist unit tests and is exposed only to unit tests. This is how that is accomplished:
function inUnitTest() {
return typeof window.QUnit === 'object';
}
var messagesModel = (function(){
//functions
var exports = {
//exported functions
};
if(inUnitTest()){
exports = $.extend({}, exports,
{
reset:function(){
messages = [];
}
}
);
}
return exports;
}());
I am using Qunit for unit tests, so during tests window.QUnit is an object so inUnitTest()
returns true and the reset function is exposed.
I've been trying to do a similar thing for my automated mocha tests. I am using yiewd which wraps Selenium webdriver. Webdriver has a function which allows you to execute arbitrary javascript. This is what I am executing:
yield driver.execute('window.automatedTesting = true');
And in the application code I have:
function inAutomatedTest() {
if(typeof window.automatedTesting === 'boolean' && window.automatedTesting) {
return true;
}
return false;
}
var messagesModel = (function(){
//functions and exports
if(inAutomatedTest()){
exports = $.extend({}, exports,
{
reset:function(){
messages = [];
}
}
);
}
return exports;
}());
I am running npm test
from the command line which runs the test script in package.json. My package.json is:
{
"devDependencies": {
"chai": "^2.3.0",
"chai-colors": "^1.0.0",
"yiewd": "^0.6.0"
},
"scripts": {
"test": "mocha --harmony --timeout 0 tests/*/*.js"
}
}
I.e. I am setting window.automatedTesting = true
in the mocha test and checking this in my application code:
describe("Test case", function() {
before(function(done) {
//set up code
});
describe("Given .....", function() {
it("Then ....", function(done) {
driver.run(function*() {
yield driver.execute('window.automatedTesting = true');
//the next function relies on messagesModel.reset() being called
yield setMessagesAsZeroMessages();
done();
});
});
});
});
However, this isn't working - inAutomatedTest()
always returns false so messagesModel.reset
is not exposed and cannot be called.
It's as though the window
object in the mocha context is different to the application code's window
object.
Am I doing something incorrectly? Is there a different, but still as simple, approach?