Angular + Jasmine,在测试和控制器之间共享服务

时间:2015-06-03 12:17:37

标签: angularjs unit-testing jasmine karma-jasmine

我测试的片段:

describe('SaleTypeCtrl', function(){
var scope, ctrl, $httpBackend;
var operator = {"OperatorId" : 24, "Number" : 4, "OperatorName" : "Heyah", "LogoUrl" : "http://www.sample.pl/logo.jpg" };

beforeEach(inject(function(_$httpBackend_, $rootScope, $controller, $state, _Sale_) {
  $httpBackend = _$httpBackend_;
  state = $state;
  scope = $rootScope.$new();
  Sale = _Sale_;
  ctrl = $controller('SaleTypeCtrl', {$scope: scope});
  Sale.setOperator(operator);
}));

it('Loads transaction types', function() {
    expect(Sale.getOperator().OperatorId).toEqualData(24); 
   $httpBackend.expectGET('api/transactionTypes?OperatorId=24').
  respond(
    [
      {"Type" : "Offline", "ButtonText" : "OFFLINE [KOD DOŁADOWUJĄCY]", "ButtonConfirmText" : "POBIERZ KOD", "Available" : true, "ConfirmationTypes" : ["Wydruk","Email"] },
      {"Type" : "Online", "ButtonText" : "ONLINE [DOŁADOWANIE]", "ButtonConfirmText" : "DOŁADUJ TELEFON", "Available" : true, "ConfirmationTypes" : ["Brak","Wydruk","Email"] }
    ]);
  $httpBackend.flush();
  expect(scope.data.TransactionTypes).toEqualData(
    [
      {"Type" : "Offline", "ButtonText" : "OFFLINE [KOD DOŁADOWUJĄCY]", "ButtonConfirmText" : "POBIERZ KOD", "Available" : true, "ConfirmationTypes" : ["Wydruk","Email"] },
      {"Type" : "Online", "ButtonText" : "ONLINE [DOŁADOWANIE]", "ButtonConfirmText" : "DOŁADUJ TELEFON", "Available" : true, "ConfirmationTypes" : ["Brak","Wydruk","Email"] }
    ]);
});

我服务的片段:

.factory('Sale', function($http){
var service = {};

service.operator = null;

service.getOperator = function(){
    return service.operator;
}

service.setOperator = function(operator){
    service.operator = operator;
}

service.getTransactionTypes = function () {
    return $http.get('api/transactionTypes', {params: {"OperatorId" : service.getOperator().OperatorId}});
}

我的控制器:

.controller('SaleTypeCtrl', function ($scope, $state, Sale) {
$scope.data = {};
$scope.loadTransactionTypes = function(){
    Sale.getTransactionTypes().success(function(transactionTypes){
        $scope.data.TransactionTypes = transactionTypes;
    }).error(function(err){
        console.error("Błąd");
    });
}
$scope.loadTransactionTypes();
})

我的测试失败了:

Sales controllers SaleTypeCtrl Loads transaction types FAILED
        TypeError: Cannot read property 'OperatorId' of null at Object.service.getTransactionTypes

Sale.setOperator(operator)为我的测试正确设置了值。

expect(Sale.getOperator().OperatorId).toEqualData(24)正确传递。

我试图以这种方式改变它:

ctrl = $controller('SaleTypeCtrl', {$scope: scope, Sale:Sale});

但它仍然没有解决我的问题。看起来控制器有不同的销售实例。

如何修改测试以设置注入控制器的工厂的初始值?

1 个答案:

答案 0 :(得分:1)

在beforeEach()中,您正在构建调用$scope.loadTransactionTypes()的控制器,调用Sale.getTransactionTypes(),执行service.getOperator().OperatorId,失败,因为运算符已在服务中设置仅在创建控制器之后。