2016-05-16 47 views
5

我的應用程序使用返回承諾的服務,該承諾通常依賴於大量其他承諾。我將它重構爲獨立的命名函數,以使測試(和可讀性)更容易。所以在這種情況下,我只想測試一下run函數是否完成它的工作並調用其他函數。在承諾解決後調用函數,但Jasmine未通過測試。爲什麼?

例如

run() { 
    return myService 
    .connection 
    .then(this.namedFunction1) 
    .then(this.namedFunction2) 
    .then(this.namedFunction3) 
    .catch((error) => { 
     console.log("doh!", error.stack); 
    }); 

當我測試名爲Function1已被稱爲茉莉失敗,即使這並非如此。這是我提出了讓事情變得簡單一點的代碼示例:

getString() { 
    return Promise.resolve("Heeeelp. Heeeelp!!"); 
    } 

    printToConsole(string) { 
    console.log(string); // This works! but Jasmine says nay :( 
    } 

    myFunction() { 
    this.getString() 
    .then(this.printToConsole) 
    .catch((error) => { 
     console.log("Some error occurred", error); 
    }); 
    } 

...和測試:

it("should call the printToConsole function", function() { 
     spyOn(myClass, "printToConsole").and.callThrough(); //added the call through so it would print 
     myClass.myFunction(); 
     expect(myClass.printToConsole).toHaveBeenCalled(); 
    }); 

和輸出...

> Started F[2016-05-16 11:32:31.898] console - Heeeelp. Heeeelp!! 
> 
> 
> Failures: 1) MyClass myFunction should call the printToConsole 
> function Message: 
>  Expected spy printToConsole to have been called. Stack: 
>  Error: Expected spy printToConsole to have been called. 

我我嘗試添加茉莉花異步完成()函數,但這沒有做任何事情,最終我在示例中立即解決了這個承諾。

那麼爲什麼或者怎麼能這個測試失敗?

任何幫助將不勝感激。謝謝。

回答

4

因爲myFunction是異步操作。 myFunction調用一個異步函數,然後立即返回,之後測試斷言激發。那時,printToConsole還沒有真正被調用過。您需要使用Jasmine's async test support才能成功運行此測試。

你需要修改myFunction返回的承諾,因此您可以知道何時完成:

myFunction() { 
    return this.getString() 
    .then(this.printToConsole) 
    .catch((error) => { 
    console.log("Some error occurred", error); 
    }); 
} 

然後你就會修改您的測試中使用的茉莉花所提供的done功能:

it("should call the printToConsole function", function(done) { 
    spyOn(myClass, "printToConsole").and.callThrough(); //added the call through so it would print 
    myClass.myFunction().then(function() { 
    expect(myClass.printToConsole).toHaveBeenCalled(); 
    done(); 
    }).catch(done); // to make sure the test reports any errors 
}); 

這應該讓事情工作。

+0

我嘗試過使用異步支持,但我的斷言不在myClass.myFunction()。then()語句中。現在它更有意義。謝了哥們。 – spryce