如何在Angular中为Karma/茉莉花测试创建存根 [英] How to create stubs for Karma/jasmine testing in Angular

查看:69
本文介绍了如何在Angular中为Karma/茉莉花测试创建存根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释如何为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.

推荐答案

您可以找到有关创建stubsspies的信息

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:

  1. 使用Stub替换实际服务.这样,您也可以在其他components.spec中重用相同的stub.因此,它创建了可重用的代码.

  1. Use Stub to replace actual service. In this way, you can reuse the same stub at other components.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆