[英]Jasmine Testing knockout.js with requirejs
我在获取Jasmine测试文件以从我的基因敲除文件中获取数据时遇到了麻烦。 我能够创建敲除的可观察对象,并在spec文件中进行测试,但不能在其他文件中进行测试。 由于某些原因,当我尝试从viewmodel.js文件访问规范文件中的mainViewModel()
,找不到该文件。 我已经包含/定义了所有requirejs文件,但是由于某种原因,它仍然无法正常工作。
这是我的代码:
viewmodel.js:
define(["knockout", "jquery"], function (ko, $) {
var data = {
Name:"The Plan",
Id: 1
};
var TestViewModel = function (data) {
var self = this;
self.planName = ko.observable(data.Name);
self.planId = ko.observable(data.Id);
return self;
}
function mainViewModel() {
var self = this;
self.plan = ko.observableArray([]);
self.plan.push(new TestViewModel(data));
}
return mainViewModel;
});
someSpec.js文件:
define(["knockout", "jquery"], function (ko, $) {
describe("MyTestSpec", function () {
var viewmodel, data;
beforeEach(function () {
require(["knockout", "jquery", "testsViewModel"], function(ko, $, tvm){
viewmodel = tvm.mainViewModel();
});
});
it("should be able to connect to View Model file", function () {
expect(viewmodel.Id).toBe(1);
});
});
});
index.html文件:
<script type="text/javascript" src="Scripts/jasmine.js"></script>
<script type="text/javascript" src="Scripts/jasmine-html.js"></script>
<script type="text/javascript" src="Scripts/boot.js"></script>
<script type="text/javascript" src="Scripts/require.js"></script>
<script type="text/javascript">
require.config({
paths: {
"jquery": './Scripts/jquery-1.10.2.min',
"knockout": './Scripts/knockout.debug',
"testViewModel" :"./Scripts/viewmodel",
}
});
// list spec files here
require(["knockout","jquery","specs/someSpec", "testViewModel"], function () {
window.onload();
});
</script>
这是您需要修复的几件事:
带回调的AMD require
函数是异步的。 这意味着只有在测试运行之后才能设置viewmodel
。 无需使用require
,只需在测试的define
调用中包含testViewModel
作为依赖项即可。 或者,您可以使用同步API形式: tvm = require('testViewModel')
。
viewmodel.js
返回mainViewModel
函数作为模块导出。 这就是在其他地方引用它时所得到的。 因此,而不是viewmodel = tvm.mainViewModel()
你会使用viewmodel = tvm()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.