我正在尝试对Angular.js服务进行单元测试,并且需要对从Mock服务返回的Promise(使用Jasmine)设置期望值。我正在使用业力单元测试框架。相关代码段如下:
// I can't figure out how to do the equivalent of a $scope.$digest here.
var loginStatusPromise = FacebookService.getFacebookToken();
loginStatusPromise.then(function(token) {
expect(false).toBeTruthy(); // If this test passes, there is something going wrong!
expect(token).not.toBeNull(); // The token should be ValidToken
expect(token).toBe('ValidToken');
});
完整的单元测试代码可以在这里看到。
问题是诺言。执行业力时,语句永远不会触发。因此,我的Expect语句均未执行。在我的控制器测试中,我使用$ scope。$ digest()来解决承诺,但是我不清楚如何在服务测试中做到这一点。正如我认为的那样,服务测试中没有“作用域”的概念。
我在这里的杆子末端错了吗?我需要在服务测试中注入$ rootScope,然后使用$ digest吗?或者,还有另一种方法吗?
假设您正在使用ngFacebook / ngModule,那么在解决方案/想法之前的快速提示是该项目没有单元测试!您确定要使用此项目吗?
我在Github上对您的单元测试进行了快速扫描,发现缺少以下内容:
1)模块初始化。ngFacebook需要此功能,或者您需要初始化执行相同功能的模块。
beforeEach(module('ngFacebook'));
或者
beforeEach(module('yieldtome'));
2)认真考虑模拟ngFacebook模块
在单元级别的测试中,您正在模拟气泡中测试您的代码,在该气泡中,外部接口被存根。
否则)请尝试添加如下所示的调用API:
$rootScope.$apply(function() {
this.FacebookService.getFacebookToken().then(function(){
//your expect code here
});
});
$httpBackend.flush();//mock any anticipated outgoing requests as per [$httpBackend][2]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句