Javascript 使用服务的控制器的Karma单元测试。离子应用
我是爱奥尼亚的新手,正在尝试测试我的控制器,它使用的是服务,但使用“$scope.order”、“$scope.stock”和控制器中包含的所有功能不断得到“未定义”。我已经分别测试了该服务,所有测试都通过了,但我无法集中精力进行控制器测试。我肯定我做错了什么。如果有人能给我一点指导,我会很感激的 controller.jsJavascript 使用服务的控制器的Karma单元测试。离子应用,javascript,angularjs,unit-testing,mocking,ionic,Javascript,Angularjs,Unit Testing,Mocking,Ionic,我是爱奥尼亚的新手,正在尝试测试我的控制器,它使用的是服务,但使用“$scope.order”、“$scope.stock”和控制器中包含的所有功能不断得到“未定义”。我已经分别测试了该服务,所有测试都通过了,但我无法集中精力进行控制器测试。我肯定我做错了什么。如果有人能给我一点指导,我会很感激的 controller.js angular.module('shop.controllers', []) .controller('StockCtrl', function($scope, Sto
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('+'));
},
};
});
我认为你的问题在于:
beforeEach(module('shop.controllers'));
您应该添加应用程序模块,而不是控制器模块
beforeEach(module('shop'));
beforeEach(module('shop'));