2017-02-21 122 views
1

我的Angular應用程序中有以下控制器。

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在這段代碼被使用,因爲它是重要的是如何某些圖像當我在渲染幻影(一個圖像渲染庫)的上下文。當我運行測試,我得到以下錯誤:

Expected spy flush to have been called. 

的具體問題,我已經是以下兩行在我的測試:

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

首先,我不相信我我正在爲$timeout調用正確的方法。在我的控制器中很清楚,我打電話$timeout,而不是$timeout.flush。其次,對於Jasmine Spys,你不能只是spyOn$timeout,因爲它需要對類和方法的引用。

所以我不太清楚如何繼續前進。我將不勝感激任何幫助 - 謝謝!

+0

'flush'是一種只存在於'ngMock'中的方法,可以從測試中調用。所以窺視刷新只會檢查你是否從測試中調用它。這是你的測試,你知道你做了/沒有,所以你爲什麼要檢查它? –

回答

1

當你寫單元測試,你必須調用$timeout.flush(),然後調用$timeout.verifyNoPendingTasks();

verifyNoPendingTasks()將拋出一個異常,如果有任何等待超時,所以基本上,你可以斷言,異常永遠不會拋出像expect(function() {$timeout.verifyNoPendingTasks()}).not.toThrow()。此外,你可以寫的期望作爲expect(function() {$timeout.flush()}).toThrow()

如果在你的控制器$timeout有一個固定的時間像$timeout(function() {}, 1000),然後在你的單元測試,你可以flush$timeout.flush(1000)

您可以在here瞭解更多。

此外,您還可以看看下面CodePen的工作示例。

+0

嗨,謝謝高拉夫!我需要監視任何事情嗎?或者我假設調用'$ timeout.flush()',然後檢查期望? – theGreenCabbage

+0

當你調用'$ timeout.flush()'時,它會清除你測試中意味着的所有'$ timeout()',你可以寫出類似'expect(function(){$ timeout)的斷言。verifyNoPendingTasks()})。not.toThrow()'。 – Gaurav

+0

不,你不需要監視任何東西,因爲'$ timeout'是你單元測試中'ngMock'提供的一個模擬服務對象。 – Gaurav

0

如果你想刺探$超時,你需要實際replace it與間諜的一種module.decorator電話。但是,您可能想問問自己,是否真正有意義地對您的指令的內部進行微觀管理。