Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 每次测试后重置服务对象_Javascript_Angularjs_Unit Testing_Angularjs Service_Karma Runner - Fatal编程技术网

Javascript 每次测试后重置服务对象

Javascript 每次测试后重置服务对象,javascript,angularjs,unit-testing,angularjs-service,karma-runner,Javascript,Angularjs,Unit Testing,Angularjs Service,Karma Runner,我正在尝试在AngularJS应用程序中测试我的身份验证服务 这是服务: 'use strict'; angular.module('testApp') .factory('Auth', function ($window, $http, $location, $q) { var currentUser; return { authenticate: function (email, password) {

我正在尝试在AngularJS应用程序中测试我的身份验证服务

这是服务:

'use strict';

angular.module('testApp')
    .factory('Auth', function ($window, $http, $location, $q) {
        var currentUser;

        return {
            authenticate: function (email, password) {
                //promise to return
                var deferred = $q.defer();

                var authRequest = $http.post('https://' + $location.host() + ':3005/authenticate', {email: email, password: password});

                authRequest.success(function (data, status, header, config) {
                    //Store currentUser in sessionStorage
                    currentUser = data;
                    $window.sessionStorage.setItem('currentUser', JSON.stringify(currentUser));
                    //resolve promise
                    deferred.resolve();
                });

                authRequest.error(function (data, status, header, config) {
                    //reject promise
                    deferred.reject('Invalid credentials.');
                });

                return deferred.promise;
            },
            isAuthenticated: function () {
                return this.getCurrentUser() !== null;
            },
            getCurrentUser: function () {
                if (currentUser !== undefined) {
                    return currentUser;
                } else {
                    currentUser = JSON.parse($window.sessionStorage.getItem('currentUser'));
                    return currentUser;
                }
            },
            logOut: function () {
                var that = this;
                $http.get('https://' + $location.host() + ':3005/logout')
                    .success(function (data, status, header, config) {
                        that.appLogOut();
                        $location.path('/login');
                    }).
                    error(function (data, status, headers, config) {
                        console.log('logout error');
                    });
            },
            appLogOut: function () {
                console.log('appside log out');
                currentUser = null;
                $window.sessionStorage.removeItem('currentUser');
            }
        };
    });
这是我的测试:

'use strict';

describe('Service: Auth', function () {

    // load the service's module
    beforeEach(module('testApp'));

    // instantiate service and any mock objects
    var Auth,
        httpBackend;

    //http://code.angularjs.org/1.2.14/docs/api/ngMock/function/angular.mock.inject
    beforeEach(inject(function (_Auth_, $httpBackend) {
        Auth = _Auth_;
        httpBackend = $httpBackend;
    }));

    // verify that no expectations were missed in the tests
    afterEach(function () {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    it('should be instantiated', function () {
        (!!Auth).should.be.true;
    });

    describe('authenticate(email, password)', function () {
        var user = {
            email: 'shaun@test.com',
            password: 'password',
            sessionId: 'abc123'
        };

        it('should make a call to the server to log the user in - and FULFILL promise if response == 200', function () {
            httpBackend.whenPOST(/https:\/\/.+\/authenticate/, {
                email: user.email,
                password: user.password
            }).respond(200, user);

            var promise = Auth.authenticate(user.email, user.password);

            httpBackend.flush();

            promise.should.eventually.be.fulfilled;
        });    
    });


    describe('isAuthenticated()', function () {
        it('should return false if user is not authenticated', function () {
            Auth.isAuthenticated().should.be.false;
        });
    });

    describe('logOut()', function () {
        it('should make a call to the server to log the user out', function () {
            // expect a GET request to be made
            // regex to capture all requests to a certain endpoint regardless of domain.
            httpBackend.expectGET(/https:\/\/.+\/logout/).respond(200);

            // call the logOut method on Auth service
            Auth.logOut();

            // flush to execute defined mock behavior.
            httpBackend.flush();
        });
    });

});
我的问题在于以下测试:

describe('isAuthenticated()', function () {
    it('should return false if user is not authenticated', function () {
        Auth.isAuthenticated().should.be.false;
    });
});
据我所知,每个“描述”和/或“it”块应该是完全独立的。我认为在每次测试之前都会注入一个新的“Auth”实例。但是,由于在运行此测试之前成功进行了身份验证测试,因此上述测试失败

因此,输出变为:

Chrome 33.0.1750 (Mac OS X 10.8.2) Service: Auth isAuthenticated() should return false if user is not authenticated FAILED
    expected true to be false
    AssertionError: expected true to be false
我错过了什么?每次测试后是否必须手动重置Auth对象?我尝试在afterEach()函数中设置Auth={},但似乎没有任何改变

感谢您抽出时间阅读此问题

更新:

我知道问题所在。在Auth.getCurrentUser()中,我从$window.sessionStorage获取“currentUser”。因此,每次测试我都会得到一个新的Auth实例(我想),但是使用了相同的$window.sessionStorage实例


现在的问题应该是……”如何在每次测试后清除$window.sessionStorage。

我最终模拟了$window对象:

    beforeEach(function () {
        // $window mock.
        windowMock = {
            sessionStorage: {
                getItem: sinon.stub(),
                setItem: sinon.spy(),
                removeItem: sinon.spy()
            }
        };

       // stub out behavior
       windowMock.sessionStorage.getItem.withArgs('currentUser').returns(JSON.stringify(user));

        module(function ($provide) {
            $provide.value('$window', windowMock);
        });
    });
测试示例:

windowMock.sessionStorage.setItem.calledWith('currentUser', JSON.stringify(user)).should.be.true;

windowMock.sessionStorage.setItem.neverCalledWith('currentUser', JSON.stringify(user)).should.be.true;

shaunlim u把我从彻底的混乱中救了出来。您是一个传奇。@shaunlim:您在哪里定义
sinon