Javascript 如何对使用AngularJS中另一个工厂的异步工厂进行单元测试?
我正试图为我的databaseContacts工厂编写一些单元测试,但对于如何实际编写它们,我感到非常困惑,因为有许多复杂的问题 这是我要测试的工厂:Javascript 如何对使用AngularJS中另一个工厂的异步工厂进行单元测试?,javascript,angularjs,unit-testing,Javascript,Angularjs,Unit Testing,我正试图为我的databaseContacts工厂编写一些单元测试,但对于如何实际编写它们,我感到非常困惑,因为有许多复杂的问题 这是我要测试的工厂: .factory('databaseContacts', function (getDatabaseContactsFromDB ){ return { getContacts: function(){ var dbContacts = getDatabaseContactsFromDB.qu
.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
});
});
我不知道如何模拟所有这些异步调用,我也没有在web上找到任何可以转换为我的场景的示例。我还觉得我的代码由于在另一个工厂中调用一个工厂而变得更加复杂。任何帮助都将不胜感激。当您打电话时,比如说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()