I am new to js unit testing and I am trying to use mocha for my backbone contact manager tutorial that i found at this github repo. However, i have a global window.ContactManager variable that I firsted wanted to test whether it exists and then test the router.on functionality inside the start function later. The variable looks like so:
window.ContactManager = {
Models: {},
Collections: {},
Views: {},
start: function(data) {
var contacts = new ContactManager.Collections.Contacts(data.contacts),
router = new ContactManager.Router();
router.on('route:home', function() {
router.navigate('contacts', {
trigger: true,
replace: true
});
});
router.on('route:showContacts', function() {
var contactsView = new ContactManager.Views.Contacts({
collection: contacts
});
.....
My test that does not work: var expect = require ('chai').expect;
describe("Application", function() {
it('creates a global variable for the name space ContactManager' , function () {
expect(ContactManager).to.exist;
})
});
How do I test and access a global window variable existence in mocha from running the tests in the console?
You are ignoring the difference between running JavaScript code in the browser and running JavaScript code in Node.
In the browser, the window
name is a reference to the object which holds all your global variables. So when you do foo = 1
in the outermost scope, you declare a global foo
, which is also accessible as window.foo
. Conversely, if you assign a new field like this: window.bar = 1
, then you have a new global called bar
.
In Node, your global object is accessed as global
. So if you do foo = 1
in the outermost scope, foo
is also accessible as global.foo
. And if you do global.bar = 1
, you have a new global named bar
.
Your code shows that you modify a window
object, which does not appear to be a reference to the global object. Options:
Run Mocha in the browser instead of in Node. See Mocha's documentation.
Set your Node environment so that it mimics enough of a browser environment to satisfy node. Setting a global window
variable to be a equal to global
might be enough but I don't know Backbone enough to know whether Backbone will be happy with this.
Run your Backbone-based code in jsdom. Jsdom provides realistic window
and document
, as if your code was running in a browser, but it has its limits. I don't know whether Backbone would be happy with those limits.