简体   繁体   中英

Error running command line Mocha using jQuery

So I have this function that uses jQuery in a file

account.js:

function getSession() {
  var session = null;
  $.ajax({
    url: "/ajax/get_session",
    async: false
  }).done(function(data, textStatus, jqXHR){
    session = data;
  });
  return session;
}

and I want to test it on the command line using Mocha. for this I have another file:

test-account.js:

var assert = require('assert');
var fs = require('fs');
var vm = require('vm');

// includes minified & uglified version, assuming mocha is run in repo root dir
var path = '../public/js/account.min.js';
var code = fs.readFileSync(path);
vm.runInThisContext(code);

describe('getSession', function() {
  it('should return the empty string because it fails', function () {
      assert.equal('', getSession());
  });
});

But when I run mocha on the command line I get the error

1 failing

1) getSession should return the empty string because it fails:

ReferenceError: $ is not defined

at getSession (evalmachine.:1:34)

at Context. (test/test-account.js:19:24)

I'm a Mocha n00b, so I wasn't exactly sure the correct direction to go in to solve this. I tried adding

var jqueryLocalPath = 'jquery.min.js';
var jqueryCode = fs.readFileSync(jqueryLocalPath);
vm.runInThisContext(jqueryCode);

before the describe call in test-account.js without success. I then tried to require it via Node.js by running

npm install jquery

and adding

var $ = require('jquery');

to the top of test-account.js before running mocha . This also did not work and I get the same error. This second method has the added disadvantage of running a newer version of jQuery (2.2.0) the the one I want to test on (1.11.3).

How can I make this test work?

I believe the answer is to use the correct Node modules , for testing.

var assert = require('assert');
var fs = require('fs');
var vm = require('vm');
var jsdom = require('mocha-jsdom'); // This is necessary for testing jQuery in Mocha

describe('mocha tests', function () {

    jsdom()

    before(function () {
        $ = require('jquery')
    });

    // includes minified & uglified version, assuming mocha is run in repo root dir
    var path = 'account.js';
    var code = fs.readFileSync(path);
    vm.runInThisContext(code);

    describe('getSession', function() {
        it('should return the empty string because it fails', function () {
            assert.equal('', getSession());
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM