mercredi 3 juin 2015

Angular + Jasmine, sharing service between tests and controller

Fragment of my test:

describe('SaleTypeCtrl', function(){
var scope, ctrl, $httpBackend;
var operator = {"OperatorId" : 24, "Number" : 4, "OperatorName" : "Heyah", "LogoUrl" : "http://ift.tt/1ANrRsD" };

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"] }
    ]);
});

Fragment of my service:

.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}});
}

My controller:

.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();
})

My test fails:

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

Sale.setOperator(operator), sets value correctly for my test.

expect(Sale.getOperator().OperatorId).toEqualData(24), passes correctly.

I tried to change it this way:

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

but it still didn't fixed my problem. It seems like controller has different instance of Sale.

How should I modify my test to set some initial values for factory injected to controller?

Aucun commentaire:

Enregistrer un commentaire