【问题标题】:External promises never finish in unit tests with ngMock外部承诺永远不会在使用 ngMock 的单元测试中完成
【发布时间】:2015-08-26 11:08:06
【问题描述】:

我正在尝试对外部承诺的解决/拒绝进行单元测试。

问题是,当ngMock 模块被注入时,这些承诺永远不会完成 - 这是强制性的,因为我正在触发 HTTP 请求和超时。

angular-pouchdb 为例,它是我项目的依赖项。从 v2.0.0 开始,由于 PouchDB promises are used,测试不再完成ngMock 被注入

示例代码,改编自angular-pouchdb tests

var scope;
beforeEach(function() {
  var $injector = angular.injector(['ng', 'ngMock', 'pouchdb']);
  var pouchDB = $injector.get('pouchDB');
  scope = $injector.get('$rootScope');
  db = pouchDB('db');
});

it('should wrap destroy', function(done) {
  db.destroy()
    .then(shouldBeOK)
    .catch(shouldNotBeCalled)
    .finally(done);

  // No matter what's used ($apply, $applySync, $timeout.flush, etc) -- the tests will never finish.
  scope.$apply();
});

上述测试的日志如下:

C:\Users\Gustavo\Projetos\main\angular-pouchdb (master)
λ karma start
INFO [karma]: Karma v0.12.37 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Windows 8 0.0.0)]: Connected on socket s1A7jIzmtcOxkGCtzYke with id 42899233
PhantomJS 1.9.8 (Windows 8 0.0.0) Angular-aware PouchDB public API should wrap destroy FAILED
        Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

所以,我的问题归结为:我在单元测试 Angular 中遗漏了什么?还是 ngMock 的内部错误?

This issue has been created in the angular-pouchdb repository as well.

【问题讨论】:

    标签: javascript angularjs angular-mock


    【解决方案1】:

    编辑 8/25:所以我们实际上已经解决了这个问题,但我仍在调查是什么原因造成的。几天后我会有更多更新的文章。

    好吧,在我的业余时间遇到这个问题几天后,我已将其缩小为 pouchDB 的第 3 方承诺中的某种异常失败,它达到 10 秒超时并且没有抛出干净错误返回。我可以通过更新我的

    jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;
    

    如果我返回并调整自定义构建并将一些登录信息登录到 pouchDB,我可以确认承诺没有在其中正确返回,我已经能够在 3.6 和 4.0 pouchDB 中复制它。从我围绕呼叫的包装控制台日志中,包装呼叫没有任何结果。在测试 3 前后,我得到了未捕获的 409 错误,因此 pouchDB 中显然有一些东西没有被正确处理。

    这是一个没有打开 ngMock 的示例,因此您可以看到没有它的情况。

    【讨论】:

    • Error: No deferred tasks to be flushed -- 另外,我可以使用 Mocha 重现同样的问题。
    • 也许为了您的测试目的,您只需要验证任何需要调用的东西,例如 $timeout.verifyNoPendingTasks()
    • 你也在 Chrome 或 PhantomJS 中测试这个,因为它可能很重要。
    • 我之前用的是 Phantom,但是 Chrome 也有同样的结果。
    • 你能把你的 package.json 贴出来让我复制一下吗?
    【解决方案2】:

    我不认为这是 ngMock 的问题,但我认为这是因为 PhantomJS 还没有准备好支持 PouchDB。

    https://github.com/ariya/phantomjs/issues/10992

    https://github.com/pouchdb/pouchdb/blob/c55db55d7edbf0821538e027399536c260af5876/docs/adapters.md

    【讨论】:

    猜你喜欢
    • 2015-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    相关资源
    最近更新 更多