D
D
Drm2015-09-02 08:30:31
Angular
Drm, 2015-09-02 08:30:31

Unit tests Angular, how to test a request to a provider?

Good day. I decided to deal with unit testing in Angular (and unit testing in general).
Testing the login form controller:

$scope.login = function(){
        $auth.login({
            user: $scope.user.name,
            password: $scope.user.password
        }).then(
          function(resp){
            console.log(resp);
            $scope.resp = resp;
            return $state.go('auth.dm');
          },
          function(){
            console.error("cant't update ");
          }
        )
    };

Accordingly, the whole task of the controller is to contact the authentication provider, passing it the data from the form ( user: $scope.user.name, password: $scope.user.password), and if the response is successful, then redirect to a certain state, if not, throw an error.
There is nothing unusual about the provider either, it just makes a request and passes data there:
login: function (params) {
          var _this = this;
          _this.initDfd();
          $http.post(configs.apiUrl, params)
            .success(function (resp) {
              _this.setAuthorized(resp);
              return _this.resolveDfd();
            })
            .error(function () {
              return _this.rejectDfd();
            });
          return _this.dfd.promise;
        },

Accordingly, I want to describe the controller in a unit test, but I can’t figure out how to do it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-09-02
Protko @Fesor

The essence of unit testing is to test only one unit at a time, everything else is mocks. That is, you need to mock the service itself and not $http

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question