【发布时间】:2014-05-30 20:44:42
【问题描述】:
我正在尝试为我的 databaseContacts 工厂编写一些单元测试,但我对如何实际编写它们非常迷茫,因为有很多复杂性。
这是我要测试的工厂:
.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;
});
}
};
})
这里是 getDatabaseContactsFromDB:
.factory('getDatabaseContactsFromDB', function ($resource){
return $resource('http://localhost:8000/contacts/');
})
这是我为测试设置的尝试:
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
});
});
我不知道如何模拟所有这些异步调用,并且我无法在网络上找到任何可以转换为我的场景的示例。我也觉得我的代码因为在另一个工厂中被调用而变得更加复杂。任何帮助将不胜感激。
【问题讨论】:
标签: javascript angularjs unit-testing