I'm trying to write some qunit unit tests for my knockout view models and I've run into an interesting issue.
In my view model I have the following function:
Get = function (id) {
return $.ajax({
url: API + "/" + id,
type: 'GET',
dataType: 'json',
timeout: Timeout,
statusCode: {
200: GetOneSuccess,
404: ItemNotFound
},
error: function () {
//Item(null);
}
});
},
Then in my unit test I have this:
vm.Get(vm.Item().Id()).then(function () {
ok(false, "Failure!");
},function () {
equal(vm.Item(), null, "Item was removed");
start();
});
ItemNotFound is as follows:
ItemNotFound = function () {
Item(null);
}
This is pretty straight forward, if the API controller returns "NotFound (Error 404)" set the Item to null. I am finding that my test if failing because when "then" is called the ItemNotFound function has not completed yet.
If I add a timeout to my unit test, it works:
vm.Get(vm.Item().Id()).then(function () {
ok(false, "Failure!");
},function () {
setTimeout(function () {
equal(vm.Item(), null, "Item was removed");
start();
}, 2000);
});
Anyone have any thoughts? Should I just not bother with the statusCodes and just handle all error types in the error handler? Doesn't seem as elegant.