无法获得茉莉花测试成功调用注入服务

时间:2015-01-18 20:57:49

标签: javascript angularjs unit-testing jasmine karma-runner

我试图用Angular围绕单元测试,我遇到了一些路障。尝试为此问题创建一个plnkr:Jasmine test fails making $httpbackend call我遇到了不同的错误。我希望如果有人可以帮助找出这个问题,那么这将有助于解决原始问题:http://plnkr.co/edit/lJTx0ldR9nEnlYbU5pJd

    (function(){'use strict';
  var RestService = function($http, $rootScope){
    var _postData = function(url, params, data, successFunction,  errorMsg, errorFunction, config) {

            if(config && config.hasOwnProperty('showLoader')){
                $rootScope.showLoader = config.showLoader;
            }

            $http({
                method: 'POST',
                url: url,
                params: params,
                data: data,
                cache: false
            })
                .success(function(data, status, headers, config) {
                    $rootScope.showLoader = false;
                    if (successFunction === undefined) {
                        _defaultSuccessFunction(data, status, headers, config);
                    }
                    else {
                        successFunction(data, status, headers, config);
                    }
                })
                .error(function (data, status, headers, config) {
                    $rootScope.showLoader = false;
                    if(status === 401){
                        _processError(data, status, headers, config, errorMsg, errorFunction);
                    }
                });
        };

        return {
            postData: _postData
        };
  };
  angular.module('ram-utilities.ui.rest.service', []).factory('RestService', ['$http', '$rootScope', RestService]);
})();

(function(){ 'use strict';
    var LoginController = function($scope, RestService){
        var _user = undefined;
        var _message = 'hello';

        var _login = function(user){
            var _success = function(response){
                _message = response.success;
                _user = response.user;
            };

            var _error = function(response){
                _message = response.success;
            };

            RestService.postData('/api/login',  null, {username: user.username, password: user.password}, _success, 'Invalid login, please try again', _error, {showLoader: true});
        };

        $scope.model = {
            login: _login,
            user: _user,
            message: _message
        };
    };

    angular.module('danny',['ram-utilities.ui.rest.service']).controller('LoginController',['$scope', 'RestService',LoginController]);
})();











describe('LoginController', function(){
    var scope, $httpBackend, controller, restService;

    beforeEach(function(){
        module('danny');
    });

    beforeEach(inject(function(_$controller_, _$rootScope_, _$httpBackend_, _RestService_){
        $httpBackend = _$httpBackend_;
        restService = _RestService_;
        scope = _$rootScope_.$new();
        controller = _$controller_('LoginController', {
            $scope: scope,
            RestService: restService
        });
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    describe('successfully logging in', function(){

       it('should redirect to /blog when authenticated', function(){

           var user = {"username":"danny@ravenartmedia.com", "password":"test"};
            expect(user.username).toEqual('danny@ravenartmedia.com');

          $httpBackend.expectPOST('/api/login', user).response(200, {});

          scope.model.login(user);
          $httpBackend.flush();

          expect(scope.model.user).not.toBe(undefined);
       });
    });
});




(function() {
  var jasmineEnv = jasmine.getEnv();
  jasmineEnv.updateInterval = 250;

  /**
   Create the `HTMLReporter`, which Jasmine calls to provide results of each spec and each suite. The Reporter is responsible for presenting results to the user.
   */
  var htmlReporter = new jasmine.HtmlReporter();
  jasmineEnv.addReporter(htmlReporter);

  /**
   Delegate filtering of specs to the reporter. Allows for clicking on single suites or specs in the results to only run a subset of the suite.
   */
  jasmineEnv.specFilter = function(spec) {
    return htmlReporter.specFilter(spec);
  };

  /**
   Run all of the tests when the page finishes loading - and make sure to run any previous `onload` handler

   ### Test Results

   Scroll down to see the results of all of these specs.
   */
  var currentWindowOnload = window.onload;
  window.onload = function() {
    if (currentWindowOnload) {
      currentWindowOnload();
    }

    //document.querySelector('.version').innerHTML = jasmineEnv.versionString();
    execJasmine();
  };

  function execJasmine() {
    jasmineEnv.execute();
  }
})();

感谢!!!

1 个答案:

答案 0 :(得分:1)

有几件事:

  1. respond

  2. 中使用response代替$httpBackend.expectPOST
  3. data参数隐藏在$http.success处理程序中 - 将其重命名为postData。也将期望的对象传递给成功回调。

  4. var _postData = function(url, params, data, successFunction /* ... */) {
        //...
    
        $http( {
            method: 'POST',
            url: url,
            params: params,
            data: data,
            cache: false
        } )
            .success( function ( postData, status, headers, config ) {
                // ...
                successFunction({
                    success: true,
                    user: data
                }, status, headers, config);
            } );
    
        //...
    }
    
    1. LoginController返回的对象只能通过$scope.model.user = response.user;等显式引用进行更改 - 只需调用_user = response.user即可更改$scope.model.user,除非您换{封闭中的{1}}。

    2. Working Plunk