dimanche 6 décembre 2015

AngularJS - Modified object does not carry from one test to the next

So I have this simple object in the service of my AngularJS app:

    this.testObj = [
        {'id': 0, 'label': 'Hello'}
    ];

called inside from .service('MainSvc', function () {

and in the controller, I have:

.controller('MainCtrl', function MainCtrl($scope, MainSvc) {
    this.testObj = MainSvc.testObj;
});

The thing is, I am doing Karma/Jasmine tests and it goes well until the 2nd test ... it does not recognize the object has changed and gets it new.

It's a mocked unit test.

describe('Mocked Unit Test', function() {
    'use strict';

    beforeEach(module('ui.router'));
    beforeEach(module('main'));

    var MainSvc, scope, http, mockMain;

    beforeEach(angular.mock.inject(function($rootScope, MainSvc, $controller, $injector){
        scope = $rootScope.$new();
        mockMain = $injector.get('MainSvc');

        $controller('MainCtrl', {
            $scope: scope,
            MainSvc: mockMain
        });

        scope.$digest();
    }));

    it('should expect item to be defined', inject(function() {
        expect(mockMain.testObj).toBeDefined(); // passes
        mockMain.testObj[1] = {id: 2, label: "World"};
        console.log(mockMain.testObj); // [Object{id: 0, label: 'Hello'}, Object{id: 2, label: 'World'}]
        console.log('Length: ' + Object.keys(mockMain.testObj).length); // Length: 2
    }));

    it('expect the testObj object to have a 2nd index', inject(function() {
        console.log(mockMain.testObj); // [Object{id: 0, label: 'Hello'}]
        console.log('Length: ' + Object.keys(mockMain.testObj).length); // Length: 1

        // Where is testObj[1] from when it was added in the first test?
    }));
});

As you can see, from the in-line comments, that the object in the second it() test does not see that the object of mockMain.testObj has changed.

Or maybe I am refrencing it wrong?

Please help. Thank you.

Aucun commentaire:

Enregistrer un commentaire