I want to unit test my function which basically builds an array of observables from an array of parameters (TypeScript code):
private BuildObservables(parameters: Parameter[]) {
var observables = {};
for (var parameterName in parameters) {
var p = parameters[parameterName];
// Build observable
observables[parameterName] = ko.observable(p.Value);
// Attach validation
if (p.IsRequired) {
observables[parameterName].extend({ required: true });
}
}
return observables;
}
My test look like this:
var parameters = [];
// new Parameter(int value, bool isRequired)
parameters["Param1"] = new Parameter("123", true);
parameters["Param2"] = new Parameter("456", false);
var viewModel = BuildObservables(parameters);
ok(viewModel["Param1"] != null);
ok(viewModel["Param2"] != null);
In case of the first parameter where isRequired
was set to true
, how to check if extension (validation) was applied ("Attach validation" part in BuildObservables)?
Edit:
In the other function I'm attaching subscribers and I don't know how to test if they were correctly attached.
I don't know much about the validation plugin for your particular case, but in more general terms i doubt it's possible to find out if an observable has been extended, since the extension mechanism is very general and does not impose a specific operation to be performed on the "extended" observable, leaving all the details of the operation to the extender itself (so the result might vary widely, ranging from wrapping the observable, subscribing to it, even simply registering the observable in an external service or anything in between).
If your problem is for unit testing purposes only, you might consider mocking the extend function so that it stores the arguments passed to it (i.e. the extenders) on the observable it is called on - this way you could later check the presence of said extenders.
For something more elaborate, the test library jasmine offer more options for mockups, including tests to check if a particular function was called and if some particular arguments were passed to it, so you might be interesting to look at it too.