Bluu
Bluu

Reputation: 41

jsdom - Option is not defined when running my mocha test

I am using node js tools for visual studio 2015 and I am writing mocha tests for my javascript and jquery, in my local environment I am using karma and chrome to run the tests and everything is working fine but for some reason I wanted to use jsdom to be able to run the tests from node js without using karma or the browser but one of the jquery plugin internally is doing an instance of Option (new Option) and using jsdom I get the reference error Option is not defined from karma I don't get any errors, the error seems obvious karma is using a real browser where the Option is defined and jsdom is not a real browser, is there any way to make my test work? debugging the test with jsdom I see that HTMLOptionElement is attached to the window object created by jsdom but maybe the interface is not fully implemented and that is why the new Option is not working.

Here is the code of the test file

if (global.window) {
    window.jQuery = window.$ = require('jquery');
} else {
    require('jsdom-global')();
    global.jQuery = global.$ = require("jquery");
}

var chai = require('chai');
var assert = chai.assert;
var expect = chai.expect;
var should = chai.should();

chai.use(require('chai-jquery'));
chai.use(require('chai-spies'));

var sourceFile = require('path_to_js_file');

describe('Test', () => {
    it('this is not passing', () => {
        var x = new Option;

        expect(1).to.equal(1);
    });

    it('this is passing', () => {
        document.body.innerHTML = '<input id="name"/>';

        sourceFile.init();

        expect($("#name").is(":focus")).to.equal(true);
    });
});

and my source file looks like this

function init () {
    $('#name').focus();
}

module.exports = {
    init
};

the error I am getting is:

ReferenceError: Option is not defined

Thank you

Upvotes: 3

Views: 1524

Answers (2)

gawi
gawi

Reputation: 2962

I encountered the same issue. I noticed that Option constructor is available from window if you assign window directly from jsdom. Below is the code that will give you access to Option constructor (however, I have to admit it's a workaround):

var jsdom = require('jsdom');
global.document = jsdom.jsdom(undefined);
global.window = document.defaultView;
global.Option = window.Option;

I'm using the latest implementation of jsdom: 9.12.0

Upvotes: 1

Alex Pearson
Alex Pearson

Reputation: 113

After running into this same issue, I noticed that the Option constructor was not, in fact, implemented in jsdom (as you suspected). See issue #1759 on GitHub. I have submitted a PR that fixes this issue.

At the time of this writing, the PR has not yet been merged, but I'll update this comment once that's been merged upstream.

Upvotes: 0

Related Questions