如何使用 RequireJS 加载模块以在像 Jasmine 这样的测试框架中进行测试?
How can I load a module with RequireJS for testing in a testing framework like Jasmine?
我是 JavaScript 的新手,尝试测试 RequireJS 模块中定义的函数。
这意味着我有一些这样的代码:
define([...], function(...){
var ModuleName = Base.extend({
init: function(){
//some code
};
});
}
现在我想测试函数init()。
我从我的 spec.js 加载对象,这有效:
describe("ModuleName", function(){
var mod = require(['../js/app/ModuleName.js'], function(ModuleName) {});
it("exists", function(){
expect(mod).toBeDefined();
});
});
这很好。
但是当我添加这段代码时,它失败了:
it("contains init", function(){
expect(mod.init).toBeDefined();
});
我不明白为什么。
你没有正确使用 RequireJS。
下面的解决方案需要用到beforeAll
,可以用this package加到Jasmine中。您的代码可能是这样的:
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
的 return 值 是对 require
本身的引用。所以是的,它已定义,但不,它不是您尝试加载的模块的值。要获取模块值,您必须像我在上面的代码中那样做。
如果您的测试恰好在 RequireJS 模块中,您也可以将要测试的模块添加到依赖项列表中:
define([..., '../js/app/ModuleName'], function (..., mod) {
describe("ModuleName", function() {
it("exists", function(){
expect(mod).toBeDefined();
expect(mod.init).toBeDefined();
});
});
});
以上两种方法我都在不同的情况下使用过。
旁注:我已经从上面代码中的模块名称中删除了 .js
。您通常不想将 .js
扩展名添加到您给 RequireJS 的模块名称中。
我是 JavaScript 的新手,尝试测试 RequireJS 模块中定义的函数。 这意味着我有一些这样的代码:
define([...], function(...){
var ModuleName = Base.extend({
init: function(){
//some code
};
});
}
现在我想测试函数init()。 我从我的 spec.js 加载对象,这有效:
describe("ModuleName", function(){
var mod = require(['../js/app/ModuleName.js'], function(ModuleName) {});
it("exists", function(){
expect(mod).toBeDefined();
});
});
这很好。 但是当我添加这段代码时,它失败了:
it("contains init", function(){
expect(mod.init).toBeDefined();
});
我不明白为什么。
你没有正确使用 RequireJS。
下面的解决方案需要用到beforeAll
,可以用this package加到Jasmine中。您的代码可能是这样的:
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
的 return 值 是对 require
本身的引用。所以是的,它已定义,但不,它不是您尝试加载的模块的值。要获取模块值,您必须像我在上面的代码中那样做。
如果您的测试恰好在 RequireJS 模块中,您也可以将要测试的模块添加到依赖项列表中:
define([..., '../js/app/ModuleName'], function (..., mod) {
describe("ModuleName", function() {
it("exists", function(){
expect(mod).toBeDefined();
expect(mod.init).toBeDefined();
});
});
});
以上两种方法我都在不同的情况下使用过。
旁注:我已经从上面代码中的模块名称中删除了 .js
。您通常不想将 .js
扩展名添加到您给 RequireJS 的模块名称中。