承诺解决后调用函数,但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 });
这应该让事情工作。
- 整合testing在Heroku爱好开发中偶尔超时
- 使用茉莉花来testingExpress.js
- 鉴于以下文件结构,如何运行基本的量angular器testing?
- NodeJS,WebStorm和Jasmine:ReferenceError:describe在debugging时没有定义
- Jasmine Nodetestingsubprocess
- 问题在JavaScript的recursion调用
- 通过幻影运行茉莉花规格,得到“无法findvariables:描述”
- 茉莉花+ Node.js服务器端unit testing。 如何运行testing?
- 在Jasmine中使用createSpy来testing模块内部的setInterval