mardi 8 décembre 2015

How Provide Dependency in Jasmine Test?

How do I provide a library dependency in a Jasmine spec so the code under test knows about the library during the unit test?

I am testing JavaScript code, that I use in a Chrome extension, with Jasmine. I run the Jasmine test from the command-line using node on OS X. I can successfully test my top-level code, which has no dependencies, this way. But when one of my JavaScript files depends on another, my Jasmine test fails. Below is a simplified example demonstrating the problem.

How do I provide FooLib in the Jasmine spec so it's available to FooMain during the unit test?

Constraints: I don't want to add any dependency injection frameworks to my FooLib and FooMain JavaScript. They run fine as they are in a Chrome extension. I also don't want to use any JavaScript build system, such as Grunt, to solve this problem.

I want to find the simplest way to test my code from the command-line. Ideally, I'll just need to revise my Jasmine spec code or maybe some Jasmine/Node config to make it work. I experimented to make FooMain see FooLib by reading then evaling the FooLib code. I was surprised this didn't work.

Top-level JavaScript code:

var FooLib;
(function (FooLib) {

    function myAdd(a,b){
        console.log(">>> myAdd() called")
        return a + b;
    }

    FooLib.myAdd = myAdd;

})(FooLib || (FooLib = {}));
exports.FooLib = FooLib;

JavaScript code that depends on the top-level code:

var FooMain;
(function (FooMain) {

    var myAddTwice = function(a,b){
        console.log(">>> myAddTwice() called")
        return FooLib.myAdd(a,b) + FooLib.myAdd(a,b);
    }

    FooMain.myAddTwice = myAddTwice;

})(FooMain || (FooMain = {}));
exports.FooMain = FooMain;

Jasmine spec file:

/////
if (typeof FooLib === "undefined") {
    console.log("1) FooLib undefined");
}
else{
    console.log("1) FooLib defined");
}

/////
fs = require('fs');
myCode = fs.readFileSync('./mystuff/myfoo-lib.js','utf-8') ;
eval(myCode);

// NOTE: doing require() after eval() 
var Testee = require('../mystuff/myfoo-main.js');
console.log("Object under test:", Testee);

///// 
if (typeof FooLib === "undefined") {
    console.log("2) FooLib undefined");
}
else{
    console.log("2) FooLib defined");
}
/////
describe("myTestSuite", function() {

    if (typeof FooLib === "undefined") {
        console.log("3) FooLib undefined");
    }
    else{
        console.log("3) FooLib defined");
    }

    it("test myAddTwice", function() {
        expect(Testee.FooMain.myAddTwice(2,3)).toBe(6);
    });
});

Jasmine Error Output:

Failures:
1) myTestSuite test myAddTwice
  Message:
    ReferenceError: FooLib is not defined
  Stack:
    ReferenceError: FooLib is not defined
        at Object.myAddTwice (.../utest/mystuff/myfoo-main.js:6:16)
        at Object.<anonymous> (.../utest/spec/foo-spec.js:38:31)

1 spec, 1 failure

Aucun commentaire:

Enregistrer un commentaire