函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
Function is called after promise is resolved but Jasmine fails the test. Why?
我的应用程序使用一个返回承诺的服务,该承诺通常依赖于一大堆其他承诺。我已经将其重构为单独的命名函数,以使测试(和可读性)更容易。所以在这种情况下,我只想测试run函数是否完成了它的工作并调用了其他函数。
例如
run() {
return myService
.connection
.then(this.namedFunction1)
.then(this.namedFunction2)
.then(this.namedFunction3)
.catch((error) => {
console.log("doh!", error.stack);
});
当我测试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);
});
}
以及测试:
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.
我尝试添加jasmine asynch done()函数,但没有成功,最终我在示例中立即解决了这个问题。
那么,为什么或者怎么会失败呢?
如有任何帮助,我们将不胜感激。谢谢
因为myFunction
是一个异步操作。myFunction
调用一个异步函数,然后立即返回,然后激发测试断言。此时,printToConsole
实际上还没有被调用。您需要使用Jasmine的异步测试支持来成功运行此测试。
您需要修改myFunction
以返回承诺,这样您就可以知道它何时完成:
myFunction() {
return this.getString()
.then(this.printToConsole)
.catch((error) => {
console.log("Some error occurred", error);
});
}
然后您将修改您的测试以使用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
});
这应该会让事情运转起来。
相关文章:
- 如何使用Jasmine测试Knockout.js点击绑定
- 如何在jasmine测试中为有角度的项目注入依赖项
- Jasmine:测试setTimeout函数会抛出一个错误
- 如何通过 phantomjs 可靠地执行利用 requirejs 的 Jasmine 测试
- 使用jasmine测试JavaScript回调函数
- Jasmine测试工厂函数调用本地函数和另一个函数-获取错误:应该是间谍,但得到了function
- 用jasmine测试JavaScriptUI的最佳方法
- 如何使用jasmine测试done和failedDeferredObject
- 在CoffeeScript文件上运行Jasmine测试时,对象未定义错误
- 使用 Jasmine 测试主干视图时,浏览器页面不断刷新
- 使用 Jasmine 测试对象中的事件处理程序
- 在 Jasmine 测试中无法访问 Angular 服务函数
- 如何正确引用Jasmine测试夹具中的图像
- jasmine测试抱怨undefined不是一个对象
- 我怎么能用jasmine测试这个代码呢
- 如何使用jasmine测试ajax响应
- 如何模拟ajax对Jasmine测试的调用
- AngularJS Jasmine测试:类型错误:'未定义'不是对象
- Jasmine测试url的javascript函数
- 使用Jasmine测试TypeScript类