Skip to content

Instantly share code, notes, and snippets.

@codethug
Last active August 29, 2015 13:57
Show Gist options
  • Save codethug/9666419 to your computer and use it in GitHub Desktop.
Save codethug/9666419 to your computer and use it in GitHub Desktop.
Testing Durandal Viewmodel that makes http call
define(['plugins/http', 'plugins/dialog', 'durandal/app', 'viewmodels/locale', 'knockout'],
function (http, dialog, app, locale, ko) {
//Note: This module exports an object.
//That means that every module that "requires" it will get the same object instance.
//If you wish to be able to create multiple instances, instead export a function.
//See the "welcome" module for an example of function export.
var engineersViewModel = function() {
var self = this;
var cachedRates = {};
self.rates = ko.observableArray();
self.loadRates = function(country) {
// If the user picked a new country
if (typeof country !== 'undefined' && country !== null && country !== "") {
if (cachedRates[country]) {
self.rates(cachedRates[country]);
} else {
// Get engineer rates from server
return http.get('api/Booking/EngineerRates').then(function(response) {
cachedRates[country] = response;
self.rates(response);
});
}
}
};
};
return new engineersViewModel();
});
describe("Engineers ViewModel", function() {
beforeEach(function() {
spyOn(http, 'get').andCallFake(function (req) {
var d = $.Deferred();
d.resolve({foo: 'bar'}); // pass in data that should be returned
return d.promise();
});
});
it("When getRates is called twice for the same country, it should only retrieve data once", function() {
return engineers.loadRates('US')
.then(function() { return engineers.loadRates('US'); })
.then(function() {
expect(http.get.callCount).toBe(1);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment