Jasmin-Karma和mocking localStorage spyOn找不到一个可以窥探getItem()的对象

时间:2015-05-19 15:11:12

标签: angularjs unit-testing jasmine

我目前正在发展为TDD并希望测试我的{ $request->only('email', 'password'); $record = \DB::table('users')->where('email', $credentials['email']->get(); $record = $record[0]; $pass = $credentials['password']; $salt = $record->salt; $pass = $pass.$salt; $hashed = hash("sha256", $pass, false); $credentials = array( 'email' => $email, 'password' => $hashed); $this->validate($request, [ 'email' => 'required|email', 'password' => 'required', ]); if ($this->auth->attempt($credentials, $request->has('remember'))) { return redirect()->intended($this->redirectPath()); } return redirect($this->loginPath()) ->withInput($request->only('email', 'remember')) ->withErrors([ 'email' => $this->getFailedLoginMessage(), ]); } 。在我的控制器内部有一个被注入的服务,称为AuthController。该服务分别使用$ localStorage AuthService bower包。我想模仿它来测试我的控制器。我是使用ngstorage提供的SpyOn完成的。作为浏览器我使用phantomjs。不幸的是,我收到了jasmine-core的错误消息:

jasmine

auth.controller.spec.coffee

Error: spyOn could not find an object to spy upon for getItem()

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

如果不注入服务,则无法访问该服务。对beforeEach的调用应该在第二个 beforeEach -> module('myApp') store = {} beforeEach inject(($controller, $rootScope, _AuthService_, localStorage) -> scope = $rootScope.$new() AuthService = _AuthService_ spyOn(localStorage, 'getItem').andCallFake (key) -> store[key] spyOn(localStorage, 'setItem').andCallFake (key, value) -> store[key] = value + '' AuthController = $controller('AuthController', $scope: scope, AuthService:AuthService) ) 内,并且应该注入服务,以便能够监视其方法:

GetWindowRect

答案 1 :(得分:1)

我找不到比使用Jasmine中的$provide模块将$localStorage服务模拟为对象更好的方法,因为此服务没有任何getter或setter 。我无法在模拟中使用Jasmine间谍,所以我所做的是为对象提供使用$localStorage服务的服务所需的内部属性。

describe("serviceThatUsengStorage", function() {
    "use strict";

    beforeEach(angular.mock.module('myApp'));

    var $serviceToTest;
    var $localStorage = {};
    var user = {
        uname: 'andre',
        pass: 'andre_pass'
    };

    beforeEach(function() {
        $localStorage.user = user;
        module(function($provide) {
            $provide.value('$localStorage', $localStorage);
        });
    });

    beforeEach(angular.mock.inject(function(_serviceToTest_) {
        $serviceToTest = _serviceToTest_;
    }));

    it("the serviceThatUsengStorage must be initilizaded using the localStorage", function() {
        expect($serviceToTest).not.toBe(null);
        expect($serviceToTest.getUserName()).toBe('andre');
        expect($serviceToTest.getUserPass()).toBe('andre_pass');
    });


});

您可以在this youtube video中看到一个非常好的示例。