I am trying to write some unit tests for my databaseContacts factory, and I am very lost as to how to actually write them, as there are a number of complications.
Here is the factory I want to test:
.factory('databaseContacts',
function (getDatabaseContactsFromDB ){
return {
getContacts: function(){
var dbContacts = getDatabaseContactsFromDB.query();
return dbContacts.$promise.then(function(result){
return result;
});
},
removeContact: function (contact){
getDatabaseContactsFromDB.remove(contact);
},
addContact: function (contact){
var addedContact = getDatabaseContactsFromDB.save(contact);
return addedContact.$promise.then(function(result){
return result;
});
}
};
})
And here is getDatabaseContactsFromDB:
.factory('getDatabaseContactsFromDB', function ($resource){
return $resource('http://localhost:8000/contacts/');
})
Here's my attempt at a setup for my test:
describe( 'databaseContacts service', function(){
var databaseContacts, httpBackend;
beforeEach(function() {
module('App.contacts');
inject (function ($httpBackend, _databaseContacts_){
databaseContacts = _databaseContacts_;
httpBackend = $httpBackend;
});
});
afterEach(function(){
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it ('should get database contacts', function (){
//somehow call databaseContacts.getContacts() and nicely mock the return data
});
});
I don't have a grasp on how one could mock all of these asynchronous calls, and I haven't been able to find any examples on the web that I can translate over to my scenario. I also feel like my code is further complicated by having a factory being called within another factory. Any help would be appreciated.
When you call, let's say getContacts, you'll have to flush $httpBackend and you have to mock response for that URL so something like this:
var storedData;
databaseContacts.getContacts().then(function(data) {
storedData = data;
});
httpBackend.expect('GET', 'http://localhost:8000/contacts/').respond(<mocked_json_here>)
httpBackend.flush()
expect(storedData).toBeDefined()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.