我正在尝试测试我的功能之一,但其中一部分使用了 Controller 中的私有(private)变量。
如何让Jasmine伪造该私有(private)变量中的数据?
window.MyApp = window.MyApp || {};
(function(myController) {
var deliverablesKoModel;
myController.initialize = function(releaseId) {
// Ajax call with this success:
deliverablesKoModel = new knockOutModel(data); // this model contains an observable array named 'deliverables'
};
myController.checkDeliverableNameIsValid = function (deliverable) {
var valid = false;
if (ko.unwrap(deliverable.name) !== null && ko.unwrap(deliverable.name) !== undefined) {
// PROBLEM HERE
// when running the test deliverablesKoModel below is always undefined!
/////////////
valid = _.all(deliverablesKoModel.deliverables(), function(rel) {
return (ko.unwrap(rel.name).trim().toLowerCase() !== ko.unwrap(deliverable.name).trim().toLowerCase()
|| ko.unwrap(rel.id) === ko.unwrap(deliverable.id));
});
}
deliverable.nameIsValid(valid);
return valid;
};
}(window.MyApp.myController = window.MyApp.myController || {}));
我的 Jasmine 测试。我尝试将liverablesKoModel设置为全局变量,但是在使用上述方法时,它始终超出范围。
describe("checkDeliverableNameIsValid should", function () {
var deliverable;
beforeEach(function () {
window['deliverablesKoModel'] = {
deliverables: function() {
return fakeData.DeliverablesViewModel.Deliverables; // this is a json object matching the deliverables in the knockout model
}
};
deliverable = {
id: 1,
name: "test 1",
nameIsValid: function(isValid) {
return isValid;
}
};
});
it("return false if any deliverable already exists with the same name", function () {
var valid = myApp.myController.checkDeliverableNameIsValid(deliverable);
expect(valid).toBe(false);
});
});
最佳答案
deliverablesKoModel
对IIFE之外的代码是私有(private)的。
我对 knockout 并不熟悉,但是有几种方法可以设置deliverablesKoModel
。
上面方法2的示例:
var deliverablesKoModel;
myController.initialize = function(releaseId, modelCallback) {
// Ajax call with this success:
deliverablesKoModel = modelCallback(data); //returns a model
};
规格:
it("return false if any deliverable already exists with the same name", function () {
var fakeModel = function(data) {
return {
deliverables: function() {
return fakeData.DeliverablesViewModel.Deliverables;
}
}
};
//You didn't initialize your
//controller, which made the "private" variable deliverablesKoModel null in your IIFE
myApp.myController.initialize(relaseId, fakeModel);
var valid = myApp.myController.checkDeliverableNameIsValid(deliverable);
expect(valid).toBe(false);
});