mercredi 1 juillet 2015

Unit testing with Karma-Jasmine: $scope.usersList not updating before test runs

I am having trouble running a unit test on an addNew() function. The addNew() function runs successfully when i test the app in the browser. But when i run my karma test, it will not show that a user has been added to the usersList when in fact, it has.

I suspected that the API Post call (.create) is not getting time to finish before the Karma test runs, so i attempted to set a timeout, but that fails as well.

Here is my addNew() function:

$scope.addNew = function addNew(newUser) {

  $scope.usersList = userService.usersList

  dataResources.create(newUser, function(data) {
    $scope.usersList.push(data);
  });

  alert('SUCCESS!');
  $state.go("UsersList");

};

Karma Test:

describe("AddUserController:", function() {

    var originalTimeout;
    var testUser3 = {firstName: 'Sammy', lastName: 'Girl', phone: '555-555-5555', email: 'sgirl@tester.com'};

    beforeEach(function() {
        originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
        jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
    });

    it("Should add a new user to usersList", function(done) {

        $scope.addNew(testUser3);
        setTimeout(function() {
            expect($scope.usersList).toEqual(testUser3);
            dump($scope.usersList)
        }, 3000);

    });

});

Here is what the message i get after running the Karma Test:

ControllerTest: AddUserController: Should Add New User FAILED
Expected [ $promise: Object({ $$state: Object({ status: 0 }) }), $resolved: false ] to equal Object({ firstName: 'Sammy', lastName: 'Girl', phone: '555-555-5555', email: 'sgirl@tester.com' })

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIME

And if I comment out 'expect($scope.usersList).toEqual(testUser3);' , dump shows usersList as empty.

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire