Mocha and jsdom - How to set a window variable

时间:2016-10-20 19:57:24

标签: testing mocha chai jsdom

I know you're not supposed to do this, but I'm trying to write some tests with legacy code still using requirejs that have a few window variables floating around.

Basically I'm trying to write a mocha test and include some predefined global variables that a different file would use later. I'm trying to do the following, but it seems the global variable "container" isn't populated when accessing it later.

global.document = require('jsdom').jsdom('<html></html>');
global.window = document.defaultView;
global.$ = require('jquery')(window);

// this should be available everywhere as far as I can tell...
global.container= {};
global.window.container= global.container;

// legacy scripts still using requirejs, so we need to load the require config here
var requirejs = require('testing-setup').requirejs;

// chai is nice
require('chai').should();

describe('model tests', function () {
    var model;

    // before we begin the tests, we need to require in all the necessary modules
    before(function (done) {
        window.container= {
            dateFormat: false
        };

        requirejs(['Model', 'common', 'date'], function (Model) {
            // load some dummy data out of a file
            model= new Model(require('./test-data.js').item);
            done();
        });
    });

    // run some more tests down here, I'll spare you those
});

The script being loaded called "common" above has a reference to the global "container" object that lives on the window. Apparently what I have is not correct. Is there no way to set up a shared global variable in jsdom? I know it's not the standard way of doing things, so please spare the lectures. Refactoring all that legacy code right now is not really a feasible option.

1 个答案:

答案 0 :(得分:0)

啊,事实证明正确的做法。似乎jsdom / nodejs区分了窗口和全局之间的区别。如果您希望在该会话的每个文件中随处可用某些内容,则需要在全局名称空间中。窗口是明确的窗口。