单元测试 – 如何对Angular服务与$cookies的交互进行单元测试?
发布时间:2020-12-17 17:48:02 所属栏目:安全 来源:网络整理
导读:我目前有一项服务,取决于$cookies中设置的变量.但是,当我想要对服务和$cookies中存储的值之间的交互进行单元测试时,则在实际初始化$cookie值之前始终初始化服务. 所以,我的问题是:如何正确地测试服务和$cookie值之间的交互? (例如:如何在我的服务初始化之
我目前有一项服务,取决于$cookies中设置的变量.但是,当我想要对服务和$cookies中存储的值之间的交互进行单元测试时,则在实际初始化$cookie值之前始终初始化服务.
所以,我的问题是:如何正确地测试服务和$cookie值之间的交互? (例如:如何在我的服务初始化之前设置$cookies中的值?) 注意:我使用Angular 1.2和Karma进行单元测试. 解决方法
我找到的唯一可以使用服务(与控制器相对)的方法是在beforeEach中设置的模块中使用$cookieStore上的装饰器.
anagular-mocks让我们以与在代码中类似的方式在规范中配置我们的模块,除了不使用config函数,我们将函数作为第二个参数传递给我们用于调用模块的模块函数.茉莉花. 它看起来像这样: describe ('my service',function () { var $cookieStore,myService beforeEach(module ('myModule',function ($provide) { // this function configures the "myModule" module before any // injectables are created. // We use a decorator to access the cookie store before other // services are instantiated. $provide.decorator ('$cookieStore',function ($delegate) { // at this point the "$cookieStore" service has only just // been constructed,and is accessible here as "$delegate". // Services that have "$cookieStore" as an injected // dependency have not been instantiated yet,so we // can slip our cookie in now. $delegate.put ('favorite-cookie','oatmeal'); return $delegate; }); })); beforeEach (inject (function (_$cookieStore_,_myService_) { myService = _myService; $cookieStore = _$cookieStore_; } it ('should interact with the pre-existing "favorite-cookie" cookie',function () { // your expectations go here. }); afterEach(function() { // clean up $cookieStore.remove ('favorite-cookie'); }); }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |