javascript - Jasmine 对 Angular $timeout 方法的单元测试

标签 javascript angularjs unit-testing jasmine karma-jasmine

我的 Angular 应用程序中有以下 Controller 。

m = angular.module "myapp.dashboards"

    m.directive "lkDashboardElement", (
      $timeout
      MyAppSettings
    )->

      scope:
        dashboard: "="
        element: "="
        dashboardController: "="
        elementLoaded: "&"

      link: ($scope, $el)->

        if MyAppSettings.shouldCalculateTableWidth

          document.addEventListener "dashboard.element.rendered", =>

            $timeout(->
              ..
              ..
            )

我删除了很多东西,所以只显示重要的部分。我遇到的问题与我对 Angular $timeout 的使用有关。 。我当前正在检查特定条件 shouldCalculateTableWidth,如果我看到事件触发,我会立即超时。

目前我正在尝试编写一个单元测试来检查是否正在使用 $timeout

这是我的测试:

describe "in a phantomjs context", ->
  beforeEach ->
    # This sets our Phantom rendering context to true for testing purposes
    MyAppSettings._setIsPhantomRendering(true)

  afterEach ->
    MyAppSettings._setIsPhantomRendering(false)

  it "uses $timeout (instead of applyAsync) for adjusting table widths", ->
    # Creates a dummy dashboard
    dashboardController.queryMap = {1: {view: "foo", model: "bar"}}
    dashboard.elements = [{id: 1}]
    spyOn($timeout, "flush")
    expect($timeout.flush).toHaveBeenCalled()

我想做的只是测试这段代码中是否使用了 $timeout ,因为当我在 Phantom 中时,某些图像的渲染方式很重要(图像渲染)库)上下文。当我运行测试时,出现以下错误:

Expected spy flush to have been called.

我遇到的具体问题是测试中的以下两行:

spyOn($timeout, "flush")
expect($timeout.flush).toHaveBeenCalled()

首先,我不认为我为 $timeout 调用了正确的方法。在我的 Controller 中非常清楚,我正在调用 $timeout,而不是 $timeout.flush。其次,对于 Jasmine Spys,您不能仅仅 spyOn $timeout,因为它需要对类和方法的引用。

所以我不太确定如何继续前进。我将不胜感激任何帮助 - 谢谢!

最佳答案

当你编写单元测试时,你必须调用$timeout.flush(),然后调用$timeout.verifyNoPendingTasks();

如果有任何挂起的超时,

verifyNoPendingTasks() 将引发异常,因此基本上,您可以断言永远不会像 expect(function () {$timeout.verifyNoPendingTasks ()}).not.toThrow()。另外,您可以将期望写为 expect(function () {$timeout.flush()}).toThrow()

如果在您的 Controller 中 $timeout 有一个固定时间,例如 $timeout(function() {}, 1000),那么在您的单元测试中您可以 刷新$timeout.flush(1000)

您可以在 here 阅读更多内容.

另外,您可以看看下面的CodePen对于工作示例。

关于javascript - Jasmine 对 Angular $timeout 方法的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42374368/

相关文章:

javascript - 从 .csv 中提取的变量不会添加

javascript - 调整 Canvas 大小而不放大元素 WEBGL

javascript - Ember 在组件内执行错误/多个操作

javascript - 搜索并将大写字母转换为小写字母并在 javascript 中插入 '' -''

javascript - 将子网格添加到 Angular ui-grid 子网格

javascript - 第二个 Angular 按钮不调用功能

c - C 中的函数模拟(用于测试)?

javascript - 如何将 <span> 值绑定(bind)到 AngularJS 或 Jquery 中的雷达图字段名称

c# - 对通过 XmlWriter 输出的函数进行单元测试?

unit-testing - 下一步是编辑触发测试吗?