我正在尝试为我的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
});
});
我不了解如何模拟所有这些异步调用,也无法在网络上找到可以转化为我的方案的任何示例。我还觉得在另一个工厂内调用一个工厂会使我的代码更加复杂。任何帮助,将不胜感激。
打电话时,假设是getContacts,则必须刷新$ httpBackend,并且必须模拟该URL的响应,如下所示:
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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句