我的应用程序使用的服务返回一个通常依赖于一大堆其他promise的promise.我已将其重构为单独的命名函数,以使测试(和可读性)更容易.所以在这种情况下,我只想测试run函数是否完成其工作并调用其他函数.
例如
run() {
return myService
.connection
.then(this.namedFunction1)
.then(this.namedFunction2)
.then(this.namedFunction3)
.catch((error) => {
console.log("doh!", error.stack);
});
Run Code Online (Sandbox Code Playgroud)
当我测试namedFunction1被称为Jasmine失败时,即使事实并非如此.这是一个我为保持简单而做的一个小代码示例:
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);
});
}
Run Code Online (Sandbox Code Playgroud)
......和测试:
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();
});
Run Code Online (Sandbox Code Playgroud)
和输出......
> Started F[2016-05-16 11:32:31.898] console - Heeeelp. Heeeelp!!
>
> …
Run Code Online (Sandbox Code Playgroud)