如何做在角测试超时工作因果报应运行 [英] how does timeout work in angular tests running in karma

查看:195
本文介绍了如何做在角测试超时工作因果报应运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢使用控制台日志反馈也许太多了,有时候我碰到,作为约定,我们已经在指令/服务/控制器增加$超时code,有时只要500毫秒,而现在的问题是单元测试过程中,我发现只有console.logs直属它构造函数将被发送到业力,并输出到屏幕上。

I love using console log for feedback perhaps too much, and sometimes I run into code that as convention we've added $timeout in the directive/service/controller, sometimes as long as 500 ms, and now the problem is during unit test, I noticed only console.logs directly under the it constructor gets sent out to karma and output to the screen.

在$超时下超时包裹控制台日志或包裹,而断言不产生任何结果,如果忽略了,有什么解决超时?

wrapped console logs under timeout or rather wrapped assertions under $timeout do not yield any result as if ignored, what's the solution to timeouts?

推荐答案

在AngularJS队,显然,不喜欢写异步单元测试。他们认为这是繁琐的编写和难以维护。

The AngularJS team, apparently, doesn't like writing asynchronous unit tests. They think it's cumbersome to write and difficult to maintain.

在你的单元测试,加载 ngMock ,这将覆盖还原最初 $超时与模拟。模拟 $超时并不像真正的JavaScript工作暂停。为了得到它调用code这里面,你必须从你的单元测试做 $ timeout.flush()

In your unit tests, you load ngMock, which overwrites the orignal $timeout with its mock. Mock $timeout doesn't work like the real JavaScript timeout. To get it to call the code that's inside it, you have to do $timeout.flush() from your unit test.

如果 $超时工作就像真正的暂停,你会一直不得不写异步单元测试使用 $超时

If $timeout worked like the real timeout, you would've had to write asynchronous unit-tests for all functions that use $timeout.

下面是一个使用一个简化的功能 $超时的一个例子,我如何测试它:

Here's an example of a simplified function that uses $timeout and how I test it:

gaApi.getReport = function() {
  report = $q.defer()

  $timeout(function() {
    $http({method: 'GET', url: 'https://www.googleapis.com/analytics/v3/data/ga'})
      .success(function(body) {
        report.resolve(body)
      })
  }, 300)

  return report.promise
}

一个单元测试:

describe('getReport', function() {
  it('should return report data from Google Analytics', function() {
    gaApi.getReport().then(function(body) {
      expect(body.kind).toBe('analytics#gaData')
    })

    $timeout.flush()
    $httpBackend.flush()
  })
})

这篇关于如何做在角测试超时工作因果报应运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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