如何在Angular中为Karma/茉莉花测试创建存根 [英] How to create stubs for Karma/jasmine testing in Angular
问题描述
任何人都可以解释如何为Angular Karma测试创建用于服务模拟的存根.请提供任何完整的示例或链接. 创建存根之后,如何使用存根数据编写测试用例.请解释.
Any one can explain how to create Stubs for service mocking for Angular Karma testing. Please provide any complete example or link. After creating the stub, how to write the test cases using stub data. Please explain.
Spy
Vs stub
是最佳实践.请提出建议.预先感谢.
Spy
Vs stub
which one is best practice. Please suggest. Thanks in advance.
推荐答案
You can find about creating stubs
and spies
in this article of mine.
关于您的第二个问题,选择存根和spy
有关实现方案的更多信息.一个可以根据情况使用在其他之上.例如:
Coming to your 2nd question, choosing stub and spy
is more about the implementation scenarios. One can used over other based on situation. For ex:
-
使用
Stub
替换实际服务.这样,您也可以在其他components.spec
中重用相同的stub
.因此,它创建了可重用的代码.
Use
Stub
to replace actual service. In this way, you can reuse the samestub
at othercomponents.spec
as well. Hence it creates reusable code.
现在,有时您的服务根据代码返回不同的值(可以说,它在某些http
调用中抛出了error
,并且您已经在代码中进行了处理).要测试这种情况,您可以简单地创建spy
并覆盖stub
响应.检查我的文章我做了同样的事情.
Now, there are times when your services returns value differently depending on code (lets say, it throws error
in some http
call and you have handled that in your code). To test such conditions, you can simple create a spy
and override the stub
response. Check my article where I have done the same.
如果快速覆盖值,请使用spy
If its a quick overriding of values, use spy
我希望它能帮上忙.
这篇关于如何在Angular中为Karma/茉莉花测试创建存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!