2013-07-18 69 views
0

我需要我的角度應用程序的測試組件。問題是我想測試的東西,每次善緣的TestRunner顯示我的錯誤:在啓動時執行ajax請求的測試角度應用程序

Error: Unexpected request: GET /foo 
No more request expected 

一些研究,很明顯的是,測試框架阻止所有請求,我需要聲明通過在我的測試中把每一個請求之後:

beforeEach(inject(function ($httpBackend) { 
    $httpBackend.expectGET("/foo").respond("bar"); 
})); 

所以我可以對請求做預期。

的問題是,它好像我不能初始化我的$ httpBackend,在這裏,像顯示後載入我的模塊/應用程序:

beforeEach(inject(function ($httpBackend) { 
    $httpBackend.expectGET("/foo").respond("bar"); 
})); 
beforeEach(module('myApplication')); 

它失敗

Error: Injector already created, can not register a module! 

但加載我模塊/應用程序先配置$ httpBackend並在此之後爲時已晚:

beforeEach(module('myApplication')); 
beforeEach(inject(function ($httpBackend) { 
    $httpBackend.expectGET("/foo").respond("bar"); 
})); 

失敗s的

Error: Unexpected request: GET /foo 
No more request expected 

它失敗,因爲我需要讓我的應用程序配置myapp.config(function(...) {.. doSomeAjax ..}

任何想法如何解決這個問題的內部的Ajax請求?

+0

發佈此問題很長時間,但想問問if – Nitesh

+0

@Nitesh我創建了第二個模塊,名爲'myApplicationTests',它具有相同的依賴關係,但用靜態替換了'myapp.config'調用,我重構了所有其他的' .config「,」.run「,」.value「和」.constant「調用另一個模塊,所以我可以在myApplication和myApplicationTests中導入它們以保持乾燥。必須是更簡單的東西 – maklemenz

回答

2

關於第一個問題:我用它

The $httpBackend used in production, always responds to requests with responses asynchronously. If we preserved this behavior in unit testing, we'd have to create async unit tests, which are hard to write, follow and maintain. At the same time the testing mock, can't respond synchronously because that would change the execution of the code under test. For this reason the mock $httpBackend has a flush() method, which allows the test to explicitly flush pending requests and thus preserving the async api of the backend, while allowing the test to execute synchronously.

:您可以載入你需要這樣的模塊:現在

var $httpBackend; // reference for your it() functions 
beforeEach(function() { 
    module('myApplication'); 

    inject(function ($injector) { 
     $httpBackend = $injector.get('$httpBackend'); 
    }); 
}); 

,約意想不到的請求問題,從angularjs httpBackend documentation有點不同,所以我的解決方案只是一個猜測。首先,我認爲你需要有一個模擬迴應。你用when()...respond()來定義它。然後,你應該刷新你的請求:

$httpBackend.expectGET("/foo").respond("bar"); 
$httpBackend.flush(); 

我用它來測試一個在工廠發出http請求的服務。在beforeEach子句中,我首先定義了模擬響應,然後實例化了服務(myservice = $injector('nameofservice'),然後我刷新了在工廠觸發的請求。)

+0

我知道這一點,我喜歡這個功能。如果我把你的第一個代碼作爲例子,我的應用程序ld是我正在開發的應用程序,它會在第3行('module('myApplication');')中發出請求,並且在第5-7行創建$ httpBackend之前執行該請求。我甚至不會到達這條線,因爲我在第3行中得到了一個異常。正如我所說的,在加載我的模塊/應用程序之前,我無法配置$ httpBackend。 – maklemenz

相關問題