【问题标题】:Mocking Cookies with Angular用 Angular 模拟 Cookie
【发布时间】:2013-10-06 21:20:36
【问题描述】:

在我的主要describe 中,我有以下内容:

beforeEach(inject(function(...) {
    var mockCookieService = {
        _cookies: {},
        get: function(key) {
            return this._cookies[key];
        },
        put: function(key, value) {
            this._cookies[key] = value;
        }
    }

   cookieService = mockCookieService;

   mainCtrl = $controller('MainCtrl', {
       ...
       $cookieStore: cookieService
   }
}

稍后我想测试控制器如何相信 cookie 是否已经存在,所以我嵌套了以下描述:

describe('If the cookie already exists', function() {
    beforeEach(function() {
        cookieService.put('myUUID', 'TEST');
    });

    it('Should do not retrieve UUID from server', function() {
        expect(userService.getNewUUID).not.toHaveBeenCalled();
    });
});

但是,当我对cookieService 进行更改时,它并没有持续到正在创建的控制器中。我是否采取了错误的方法?

谢谢!

编辑:更新了测试代码,这就是我使用 $cookieStore 的方式:

var app = angular.module('MyApp', ['UserService', 'ngCookies']);

app.controller('MainCtrl', function ($scope, UserService, $cookieStore) {
var uuid = $cookieStore.get('myUUID');

if (typeof uuid == 'undefined') {
    UserService.getNewUUID().$then(function(response) {
        uuid = response.data.uuid;
        $cookieStore.put('myUUID', uuid);
    });
}

});

【问题讨论】:

  • 你能说明 $cookieStore 在你的控制器中是如何使用的吗?以及如何测试控制器?
  • 已更新,如果您需要更多测试代码,请告诉我。
  • “它没有持久化到控制器中”是什么意思?你想说你的控制器没有使用模型吗?或者你的意思是当你打电话给$cookieStore.get()时,你不能得到期望值?
  • 如果我在该嵌套描述块的beforeEach 中调用cookieService.put(...),那么当我在控制器中记录$cookieStore.get(...) 时,它返回为未定义,就好像它没有看到我的cookie我正在尝试模拟。
  • 我明白了。确保控制器实际上正在调用模拟的方法。如果可以,请尝试创建一个 plunk 或 fiddle,这将有很大帮助。

标签: angularjs cookies jasmine


【解决方案1】:

您的单元测试不必创建一个模拟 $cookieStore 并从本质上重新实现其功能。您可以使用 Jasmine 的 spyOn 函数创建一个 spy 对象并返回值。

创建一个存根对象

var cookieStoreStub = {};

在创建控制器之前设置你的间谍对象

spyOn(cookieStoreStub, 'get').and.returnValue('TEST'); //Valid syntax in Jasmine 2.0+. 1.3 uses andReturnValue()

mainCtrl = $controller('MainCtrl', {
 ... 
 $cookieStore: cookieStoreStub 
}

为 cookie 可用的场景编写单元测试

describe('If the cookie already exists', function() {
    it('Should not retrieve UUID from server', function() {
        console.log(cookieStore.get('myUUID')); //Returns TEST, regardless of 'key'
        expect(userService.getNewUUID).not.toHaveBeenCalled();
    });
});

注意:如果您想测试多个 cookieStore.get() 场景,您可能希望将控制器的创建移到 describe() 块内的 beforeEach() 中。这允许您调用 spyOn() 并返回适合于描述块的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    相关资源
    最近更新 更多