Angular.js承诺在使用业力进行单元测试服务时无法解决 [英] Angular.js promise not resolving when unit testing service with karma

查看:62
本文介绍了Angular.js承诺在使用业力进行单元测试服务时无法解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对Angular.js服务进行单元测试,并且需要对从Mock服务返回的promise(使用Jasmine)设置一个期望值。我正在使用业力单元测试框架。相关的代码片段如下:

I am trying to unit test an Angular.js service, and need to set an expect on a promise returned from a Mock service (using Jasmine). I am using the karma unit testing framework. The relevant code snippet is below:

// 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');
});

可以看到完整的单元测试代码这里

The complete unit test code can be seen here.

问题是当业力执行时,promise.then语句永远不会触发。因此,我的期望陈述都没有被执行。
在我的控制器测试中,我使用$ scope。$ digest()来解决这些承诺,但我不清楚在服务测试中如何做到这一点。我认为在服务测试中没有范围的概念。

The problem is the promise.then statement never fires when karma is executing. Hence, none of my expect statements are executed. In my controller tests, I use $scope.$digest() to resolve the promises, but I am not clear on how to do this in a service test. As I thought there was no notion of 'scope' in a service test.

我在这里有错误的结尾吗?我是否需要将$ rootScope注入我的服务测试,然后使用$ digest?或者,还有另一种方法吗?

Do I have the wrong end of the stick here? Do I need to injecct $rootScope into my service test and then use $digest? Or, is there another way?

推荐答案

假设您正在使用 ngFacebook / ngModule 在解决方案/想法之前快速说明该项目没有单元测试!你确定要使用这个项目吗?

Assuming that you are using ngFacebook/ngModule a quick note before the solution/ideas is that this project does not have unit tests ! Are you sure you want to use this project ?

我在Github上快速扫描了你的单元测试,发现以下缺失: -

I did a quick scan of your Unit Tests on Github and found following missing:-

1)模块初始化
ngFacebook需要或你需要初始化你做同样事情的模块。

1) Module initialization. ngFacebook needs that or you need to initialize your module that does the same thing.

beforeEach(module('ngFacebook'));

OR

beforeEach(module('yieldtome'));

2)认真考虑模仿ngFacebook模块

在单元级别测试中,您正在模拟气泡中测试代码,其中外部接口被删除。

At unit level tests you are testing your code within a mocked bubble where outside interfaces are stubbed out.

否则)尝试添加调用API,如下所示: -

Otherwise) Try adding calling the API as below:-

 $rootScope.$apply(function() {
     this.FacebookService.getFacebookToken().then(function(){
        //your expect code here
     });
    });
 $httpBackend.flush();//mock any anticipated outgoing requests as per [$httpBackend][2]

这篇关于Angular.js承诺在使用业力进行单元测试服务时无法解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆