我目前正在阅读名为“使用 AngularJS 掌握 Web 应用程序开发”的书,其中一个示例中有一个名为“聚合回调”的测试。
我遇到问题的示例包含 Person 对象:
var Person = function(name, $log) {
this.eat = function(food) {
$log.info(name + ' is eating delicious ' + food);
};
this.beHungry = function(reason) {
$log.warn(name + ' is hungry because: ' + reason);
};
};
名为 Restaurant 的对象:
var Restaurant = function($q, $rootScope) {
var currentOrder;
return {
takeOrder : function(orderedItems) {
currentOrder = {
deferred : $q.defer(),
items : orderedItems
};
return currentOrder.deferred.promise;
},
deliverOrder : function() {
currentOrder.deferred.resolve(currentOrder.items);
$rootScope.$digest();
},
problemWithOrder : function(reason) {
currentOrder.deferred.reject(reason);
$rootScope.$digest();
}
};
};
最后是聚合回调的测试:
it('should allow callbacks aggregation', function() {
var pizzaPid = new Restaurant($q, $rootScope);
var pizzaDelivered = pizzaPid.takeOrder('Margherita');
pizzaDelivered.then(pawel.eat, pawel.beHungry);
pizzaDelivered.then(pete.eat, pete.beHungry);
pizzaPid.deliveryOrder();
expect($log.info.logs).toContain(['Pawel is eating delicious Margherita']);
expect($log.info.logs).toContain(['Pete is eating delicious Margherita']);
});
正如您所看到的,测试没有显示项目是如何添加/注入到测试中的,而且我对 TDD 的一般概念还是陌生的。
我最终所做的是将这些全局对象转换为服务和工厂:
angular.module('myApp', [])
.service('Person', function(personName, $log) {
this.eat = function(food) {
$log.info(personName + ' is eating delicious ' + food);
};
this.beHungry = function(reason) {
$log.warn(personName + ' is hungry because: ' + reason);
};
})
.factory('Restaurant', function($q, $rootScope) {
var currentOrder;
return {
takeOrder : function(orderedItems) {
currentOrder = {
deferred : $q.defer(),
items : orderedItems
};
return currentOrder.deferred.promise;
},
deliverOrder : function() {
currentOrder.deferred.resolve(currentOrder.items);
$rootScope.$digest();
},
problemWithOrder : function(reason) {
currentOrder.deferred.reject(reason);
$rootScope.$digest();
}
};
});
但是现在我正在努力使用服务的多个实例来代表我的测试中的“pawel”和“pete”:
describe('Person and Restaurant tests', function() {
var Person;
var Restaurant;
var $q;
var $rootScope;
var $log;
beforeEach(function() {
module('myApp');
module(function($provide) {
$provide.value('personName', 'Pawel');
});
inject(function(_Person_, _Restaurant_, _$q_, _$rootScope_, _$log_) {
Person = _Person_;
Restaurant = _Restaurant_;
$q = _$q_;
$rootScope = _$rootScope_;
$log = _$log_;
});
});
it('should allow callbacks aggregation', function() {
var pizzaDelivered = Restaurant.takeOrder('Margherita');
// here's where the problem is
// with current set up I can only call it as
// pizzaDelivered.then(Person.eat, Person.beHungry);
pizzaDelivered.then(pawel.eat, pawel.beHungry);
pizzaDelivered.then(pete.eat, pete.beHungry);
Restaurant.deliveryOrder();
expect($log.info.logs).toContain(['Pawel is eating delicious Margherita']);
expect($log.info.logs).toContain(['Pete is eating delicious Margherita']);
});
});
正如我所说 - 我是新手,希望能得到一些帮助。