[英]Testing javascript function with qunit
I declare a ViewModel within a javascript file as per below. 我按照下面的JavaScript文件中声明一个ViewModel。
(function(root) {
var ko = root.ko;
var vm = {
modelType: ko.observable(),
message : ko.observable(),
toolbarIsVisible : ko.observable(true),
isDataDirectoryManager : ko.observable(true),
listItems : ko.observableArray(),
ko.applyBindings(vm);
};
}(window));
In my unit test js file I reference qunit.js and the js file with the vm. 在我的单元测试js文件中,我引用qunit.js和带有vm的js文件。 How do I construct a test to inspect the value of (say) toolbarIsVisible.
如何构造测试以检查(例如)toolbarIsVisible的值。 I can't seem to write the correct syntax to reference the vm variable in my test.
我似乎无法在测试中编写正确的语法来引用vm变量。
Thanks Martin 谢谢马丁
Its a closure, so only way to get it from a test is to mock ko.applyBindings and retrive the vm value from there. 它是一个闭包,因此从测试中获取它的唯一方法是模拟ko.applyBindings并从那里获取vm值。
But I really think you should make your VM's public like this 但我真的认为您应该像这样公开您的VM
(function(ko, MyApp) {
MyApp.ViewModel = {
modelType: ko.observable(),
message : ko.observable(),
toolbarIsVisible : ko.observable(true),
isDataDirectoryManager : ko.observable(true),
listItems : ko.observableArray()
};
ko.applyBindings(ViewModel);
}(window.ko, window.MyApp = window.MyApp || {}));
edit: Another tip is not to use object literals but prototype objects like 编辑:另一个技巧是不使用对象文字,而是使用原型对象
MyApp.ViewModel = function() {
this.modelType = ko.observable();
};
MyApp.ViewModel.prototype = {
foo: function() {
}
};
edit: Qunit example 编辑:Qunit示例
test("When model is valid", function() {
var model = MyApp.ViewModel();
model.value("Valid value");
equal(model.canSave(), true, "You should be able to save");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.