【发布时间】:2015-08-02 14:21:07
【问题描述】:
我是 Ionic 的新手,我正在尝试测试我的控制器,该控制器正在使用一项服务,但使用 '$scope.order'、'$scope.stock' 和我的控制器中包含的所有功能不断得到“未定义”。我已经单独测试了该服务,所有测试都通过了那里,但无法理解控制器测试。我确定我做错了什么。如果有人能指导我一点,将不胜感激。
controller.js
angular.module('shop.controllers', [])
.controller('StockCtrl', function($scope, Stock) {
$scope.stock = Stock.all();
$scope.order = Stock.order();
$scope.showTotalPrice = function() {
$scope.total = Stock.total();
}
$scope.addToBasket = function(chatId){
Stock.update(chatId);
Stock.updateBasket(chatId);
}
});
service.js
angular.module('shop.services', [])
.factory('Stock', function() {
var order = [];
var prices = [];
var total = 0;
var items = [{
id: 0,
name: "Black Shoes",
price: 50,
quantity: 7
},
{
id: 1,
name: "Blue Shoes",
price: 10,
quantity: 2
},
{
id: 2,
name: "Green Shoes",
price: 14,
quantity: 5
},
{
id: 3,
name: "Red Flip Flops",
price: 9,
quantity: 6
}
}];
return {
all: function() {
return items;
},
get: function(itemId) {
for (var i = 0; i < items.length; i++) {
if (items[i].id === parseInt(itemId)) {
return items[i];
}
}
return null;
},
update: function(itemId) {
for (var i = 0; i < items.length; i++) {
if (items[i].id === parseInt(itemId)) {
return items[i].quantity -= 1;
}
}
return null;
},
updateBasket: function(itemId) {
for (var i = 0; i < items.length; i++) {
if (items[i].id === parseInt(itemId)) {
order.push({name: items[i].name, price: items[i].price});
prices.push(items[i].price);
}
}
return null;
},
order: function() {
return order;
},
total: function() {
return total = eval(prices.join('+'));
},
};
});
controller.spec.js
describe('Controllers', function(){
var scope;
var control;
var StockMock;
beforeEach(module('shop.controllers'));
beforeEach(function(){
StockMock = jasmine.createSpyObj('Stock', ['all', 'get', 'update', 'updateBasket', 'order'])
inject(function($rootScope, $controller){
scope = $rootScope.$new();
control = $controller('StockCtrl', {$scope: scope, Stock: StockMock});
});
});
it("should have a scope variable defined", function() {
expect(scope).toBeDefined();
});
});
【问题讨论】:
标签: javascript angularjs unit-testing mocking ionic