承诺解决后调用函数,但Jasmine不通过testing。 为什么?

我的应用程序使用一个服务,返回一个通常依赖于一大堆其他承诺的承诺。 我已经将这个重构成单独的命名函数,使testing(和可读性)更容易。 所以在这种情况下,我只想testing一下run函数是否完成了它的工作并调用其他函数。

例如

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

当我testingnamedFunction1被称为茉莉花失败时,尽pipe事实并非如此。 下面是我为保持简单而编写的一个小代码示例:

 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); }); } 

…和testing:

 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. 

我尝试添加茉莉花asynchronous完成()函数,但是这没有做任何事情,最终我在例子中立即解决这个承诺。

那么为什么或怎么能这个testing失败呢?

任何帮助将不胜感激。 谢谢。

因为myFunction是一个asynchronous操作。 myFunction调用一个asynchronous函数,然后立即返回,之后testing断言激发。 那时, printToConsole还没有真正被调用。 你会想要使用Jasmine的asynchronoustesting支持来成功运行这个testing。

您需要修改myFunction来返回承诺,以便知道何时完成:

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

然后,您将修改您的testing以使用Jasmine提供的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 }); 

这应该让事情工作。