How can I load a module with RequireJS for testing in a testing framework like Jasmine?

╄→尐↘猪︶ㄣ 提交于 2019-12-12 01:54:10

问题


I am new to JavaScript and try to test functions defined in a RequireJS Module. That means i have some code like this:

define([...], function(...){
    var ModuleName = Base.extend({
        init: function(){
            //some code
        };
    });
}

Now I want to test the function init(). I load the object from my spec.js, this works:

describe("ModuleName", function(){
    var mod = require(['../js/app/ModuleName.js'], function(ModuleName) {});

    it("exists", function(){
        expect(mod).toBeDefined();
    });
});

This passes well. But when I add this code, it fails:

it("contains init", function(){
    expect(mod.init).toBeDefined();
});

I don't understand why.


回答1:


You're not using RequireJS properly.

The following solution needs the use of beforeAll, which can be added to Jasmine with this package. Your code could be something like this:

describe("ModuleName", function() {
    var mod;

    beforeAll(function (done) {
        // This loads your module and saves it in `mod`.
        require(['../js/app/ModuleName'], function(mod_) {
            mod = _mod;
            done();
        });
    });

    it("exists", function(){
        expect(mod).toBeDefined();
        expect(mod.init).toBeDefined();
    });
});

As I recall, the return value of require called with an array of dependencies is a reference to require itself. So yes, it is defined but, no, it is not the value of the module you were trying to load. To get a module value, you have to do something like I did in the code above.

If your tests happen to be in a RequireJS module, you could also just add the module to be tested to the list of dependencies:

define([..., '../js/app/ModuleName'], function (..., mod) {
    describe("ModuleName", function() {
        it("exists", function(){
            expect(mod).toBeDefined();
            expect(mod.init).toBeDefined();
        });
    });
});

I've used both methods above in different circumstances.

Side note: I've removed the .js from the module name in the code above. You generally do not want to put the .js extension to module names you give to RequireJS.



来源:https://stackoverflow.com/questions/29648543/how-can-i-load-a-module-with-requirejs-for-testing-in-a-testing-framework-like-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!