vendredi 5 février 2016

Angular unit test .catch block

I have a controller and service for which i write unit test for. The service perform http request, controller has .then and .catch block. I can test .then block no problem, but how to test .catch?

Controller:

$scope.performPost = function (action) {

    $scope.shoppingCart = function() {
        $scope.loading = true;
        $scope.acText = '';

        myService.postAction('cart', $scope.myData)
            .then(function(data) {
                $timeout(function(){
                    $scope.loading = false;
                    $scope.tick = true;
                }, 1500);
            })
            .catch(function() {
                $scope.errorException();
            });
    };

    switch(action) {
        case "viewShoppingCart":
            $scope.shoppingCart();
            break;
        case "updateProfile":
            $scope.updateUserDetails();
            break;
    }
};

Test for .then:

describe("MyController Tests", function() {

    var scope;
    var ctrl;

    var customer = {
            "accountId" : "12345678901",
            "firstName" : "Joe",
            "lastName" : "Bloggs",
    };

    var unlockRespone = {};

    beforeEach(inject(function($rootScope, $controller, myService, _$q_, $httpBackend, $timeout) {
        scope = $rootScope.$new();
        rootScope = $rootScope;
        mockMyService = myService;
        pingUrl = "http://server:80/ping";
        httpBackend = $httpBackend;
        timeout = $timeout;    

        var unlockDeferred = _$q_.defer();
        unlockDeferred.resolve(unlockRespone);
        spyOn(mockMyService, 'postAction').and.returnValue(unlockDeferred.promise);

        spyOn(rootScope, '$broadcast').and.callThrough();

        ctrl = $controller('MyController', {$scope:scope, myService:mockMyService});

        spyOn(scope, 'performPost').and.callThrough();
    }));   

    it("Should call the viewShoppingCart function", function() {
        httpBackend.expectGET(pingUrl).respond({ status: "OK" });
        scope.performPost('viewShoppingCart');
        timeout.flush(4000);
        expect(scope.loading).toBeFalsy();
        expect(scope.tick).toBeTruthy();   
    });
});

Aucun commentaire:

Enregistrer un commentaire