无法让茉莉花测试成功调用注入的服务

Cannot get jasmine test to succeed calling injected service

本文关键字:调用 注入 服务 成功 测试 茉莉花      更新时间:2023-09-26

我试图用Angular进行单元测试,但我遇到了一些障碍。 在尝试为此问题创建 plnkr 时:茉莉花测试失败$httpbackend调用我遇到了不同的错误。 我希望如果有人能帮助弄清楚这个 plunkr,这将有助于解决最初的问题: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. $httpBackend.expectPOST中使用respond而不是response

  2. data参数隐藏在处理程序$http.success - 将其重命名为 postData .同时将预期对象传递给成功回调。

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,除非您将_user包装在闭包中。

  2. 工作普伦克