简体   繁体   中英

Including external .js files for unit tests

I am trying to run coverage tests for my JavaScript unit tests (written in QUnit [not my idea, legacy project]) and run them via command line. Problem i am facing is references to external bits of code. Look at example bellow:

Code:

var DateHelper = function() {
return {
    GetUtcDate: function (date) {
            if (DateTypeChecker.Data["date"]) {
                return new Date();
            }
            return date;
    }
}    

Test:

QUnit.test('GetUtcNow - compare UTC date', function(assert) {
  var currentUtcDate = DateHelper.GetUtcNow();
  var nowDate = new Date();

  assert.equal(nowDate.getUTCFullYear() == currentUtcDate.getFullYear(), 'dates are the same');
});

So a very simple test that checks two dates, this works lovely when run in the browser, because the external javascript file containing DateTypeChecker is loaded in the HEAD. But this test fails in the command line as node (or w/e is performing the test) doesn't have a reference to DateTypeChecker object.

My question is, how do i fix this, so that the file for DateTypeChecker is loaded/required? (i know that i can do this with RequireJS, but i don't wan't to add more dependencies and frameworks)

I think this is a general question for js unit testing (not just QUnit).

Two options: (a) mock out the external dependency or (b) actually include the external dependency JS file. For the second option (b), I would use a test runner like Karma and hook up QUnit to it. The configuration is pretty straight forward on that linked site.

The first option (a) is what I would recommend, however. It makes your tests more idempotent and thus loosely coupled. In QUnit you can set up a mock pretty easy, we just use a simple beforeEach function:

QUnit.module( "testing DateHelper", {
  beforeEach: function() {
    // before each test runs, we can create a "fake" DateTypeChecker
    // Note that it doesn't matter what this thing does, so long as it 
    // satisfies your dependency in the DateHelper
    window.DateTypeCheker = {
      Data: { date: true }
    };
  }
});

QUnit.test( ... ); // your normal stuff

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