如何在像Jasmine这样的测试框架中加载带有RequireJS的模块进行测试? [英] How can I load a module with RequireJS for testing in a testing framework like Jasmine?

查看:239
本文介绍了如何在像Jasmine这样的测试框架中加载带有RequireJS的模块进行测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的新手,并尝试测试RequireJS模块中定义的函数。
这意味着我有一些这样的代码:

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
        };
    });
}

现在我想测试函数init()。
我从我加载对象spec.js,这是有效的:

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();
});

我不明白为什么。

推荐答案

你没有正确使用RequireJS。

You're not using RequireJS properly.

以下是这样的lution需要使用 beforeAll ,可以使用此包。你的代码可能是这样的:

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();
    });
});

我记得,返回值使用依赖数组调用的require 是对 require 本身的引用。所以是的,它被定义但是,不,它不是您尝试加载的模块的值。要获得模块值,您必须执行上面代码中的操作。

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.

如果您的测试碰巧在RequireJS模块中,您也可以添加要测试的模块依赖项列表:

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.

附注:我已从上面代码中的模块名称中删除了 .js 。您通常不希望将 .js 扩展名放到您为RequireJS提供的模块名称。

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.

这篇关于如何在像Jasmine这样的测试框架中加载带有RequireJS的模块进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆