AngularJS模块NgMockE2E的passThrough()方法不起作用

时间:2016-12-23 11:22:44

标签: javascript angularjs http jasmine ngmock

我在 angular-js 中有一个 sails node-js 应用程序,我决定对它进行一些测试,特别是在后端部分,我正在使用 Jasmine ngMockE2E 工具,因为我想用一些真实的服务器端数据来测试它。

以下是我要测试的代码的一部分:

app.controller('IdentificationCtrl', function($scope, $rootScope, ... , ajax) {

    _initController = function() {
        $scope.loginData = {};
    };

    $scope.doLogin = function(form) {
        if (form.$valid) {
            ajax.sendApiRequest($scope.loginData, "POST", "session/login").then(
                function(response) {
                    //$state.go('app.dashboard');
                    window.localStorage.setItem("sesion", JSON.stringify(response.data));
                    $rootScope.userTest = response.data;
                },
                (function(error) {
                    console.log("error")
                })
            );
        }
    };

    _initController();

});

这是我的 service.js 文件,其中我提供了ajax服务:

angular.module('common.services', [])
.service('ajax', function($http, $rootScope) {

    if (window.location.hostname == "localhost") {
        var URL = "http://localhost:1349/";
    } else {
        var URL = "http://TheRealURL/";
    }

    this.sendApiRequest = function(data, type, method) {
        $rootScope.$broadcast('loading:show')
        if (method == "session/login" || method == "session/signup") {
            var authorization = "";
        } else {
            var authorization = JSON.parse(window.localStorage["sesion"]).id;
        }

        data_ajax = {
            url: URL + method,
            method: type,
            headers: {
                'Content-Type': 'text/plain',
                'authorization': authorization
            }
        }

        if (type === "GET" || type != "delete") {
            data_ajax.params = data;
        } else {
            data_ajax.data = data;
        }

        if (window.localStorage['admin-language']) {
            data_ajax.headers['accept-language'] = window.localStorage['admin-language'];
        } else {
            data_ajax.headers['accept-language'] = window.navigator.language.toUpperCase();
        }

        //The test arrives here perfectly
        return $http(data_ajax).success(function(data, status, headers, config) {
            //But does not enter here 
            return data;
            $rootScope.$broadcast('loading:hide')
        }).error(function(data, status, headers, config) {
            //Nor here
            return data;
            $rootScope.$broadcast('loading:hide')
        });
        //And finally achieves this point, but without making the http call
    }
})

这是我加载 Jasmine ngMocks 和测试文件的html:

...
<!-- Testing files -->
<link rel="stylesheet" type="text/css" href="lib/jasmine-core/jasmine.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine-html.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/boot.min.js"></script>
<script type="text/javascript" src="lib/angular-mocks/angular-mocks.js"></script>
<script src="js/TestBackend.js"></script>
...

这是上面提到的 testBackend.js 文件,我打算在其中进行测试:

describe('FirstCycleController', function() {

beforeEach(module('myApp'));
beforeEach(module('ngMockE2E'));

var $controller;
var $rootScope;
var $httpBackend;

beforeEach(inject(function(_$controller_, _$rootScope_, _$httpBackend_) {

    $controller = _$controller_;
    $rootScope = _$rootScope_;
    $httpBackend = _$httpBackend_;
}));
    describe('User login', function() {
        it('verifys that a user is correctly logged.', inject(function() {
            var $identificationScope = {};
            var identificationController = $controller('IdentificationCtrl', { $scope: $identificationScope });

            var form = {
                $valid: true
            }

            $identificationScope.loginData = {
                email: 'user@test.com',
                password: 'usertest'
            };

             $rootScope.userTest = null;

            //pass through everything
            $httpBackend.whenGET(/^\w+.*/).passThrough();
            $httpBackend.whenPOST(/^\w+.*/).passThrough();

            //call the login function simulating a login
            $identificationScope.doLogin({ $valid: true });

            setTimeout(function() {

                expect($rootScope.userTest).not.toBe(null);

            }, 150);
        }));
    });
});

问题是,在运行 testBackend.js 测试文件时, 不会进行任何 http调用。似乎 passThrough()功能无法正常工作。

我面对并纠正了未定义 passThrough()功能的问题,这是因为我没有加载 ngMockE2E 模块(而不是 ngMock )。但这次 Jasmine 工作正常,错误只是规范是假的:

Error: Expected null not to be null.

如果此问题已经解决,请致歉,我无法在任何地方找到解决方案。

1 个答案:

答案 0 :(得分:0)

有关角度github issue

的详细讨论