在节点的mocha js中使用全局窗口variables

我是新来的jsunit testing,我正在尝试使用mocha作为我在这个github仓库find的主干联系人pipe理器教程。 然而,我有一个全局window.ContactManagervariables,我初审想testing它是否存在,然后testing启动function后面的router.onfunction。 variables看起来像这样:

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 }); ..... 

我的testing不起作用:var expect = require('chai')。expect;

 describe("Application", function() { it('creates a global variable for the name space ContactManager' , function () { expect(ContactManager).to.exist; }) }); 

我如何在控制台中运行testing来testing和访问mocha中存在的全局窗口variables?

您忽略了在浏览器中运行JavaScript代码和在Node中运行JavaScript代码之间的区别。

在浏览器中, window名称是对所有全局variables的引用。 所以当你在最外层的范围中做foo = 1时,你声明了一个全局的foo ,它也可以被window.foo访问。 相反,如果你指定一个新的字段是这样的: window.bar = 1 ,那么你有一个新的全局调用bar

在Node中,您的全局对象以global方式访问。 所以如果你在最外层的范围中做foo = 1foo也可以作为global.foo访问。 如果你做global.bar = 1 ,你有一个新的全局命名bar

您的代码显示您修改window对象,该window对象似乎不是对全局对象的引用。 选项:

  1. 在浏览器中而不是在节点中运行Mocha。 查看摩卡的文档 。

  2. 设置您的节点环境,以便它足够模仿浏览器环境以满足节点。 设置一个全局windowvariables等于global 可能就足够了,但是我不知道Backbone是否足以知道Backbone是否会对此感到满意。

  3. 在jsdom中运行基于骨干的代码。 Jsdom提供了逼真的windowdocument ,就好像您的代码在浏览器中运行一样,但却有其局限性。 我不知道Backbone是否会满意这些限制。

另一个解决scheme是使用https://www.npmjs.com/package/window-or-global

 import React, { Component } from 'react' // in node, you'll get the global object instead of crashing by an error import root from 'window-or-global' class MyComponent extends Component { // this method is only invoked in the browser environment componentDidMount() { root.addEventListener(/*...*/) } componentWillUnmount() { root.addEventListener(/*...*/) } render() {} } // Voilà. Enjoy your universal react component! ;) // No more 'window is not defined' errors when you render your component // on server side. 

要安装,运行npm install --save window-or-global