在使用Jasmine进行单元测试时,我应该模拟或监视或存根注入到组件中的服务吗? [英] While doing Unit testing with Jasmine should I mock or spy or stub my service which is injected in my component?

查看:70
本文介绍了在使用Jasmine进行单元测试时,我应该模拟或监视或存根注入到组件中的服务吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的component.ts中,服务已注入到组件的构造函数中,该构造函数订阅了服务中的功能并接收信息.在这种情况下,我该如何测试我的组件?

In my component.ts the service has been injected in the constructor of the component which subscribe to a function in the service and receives information. How can I test my component in that case?

在component.ts中,我有以下代码:-

In the component.ts I have the following code :-

在这种情况下我该如何进行?

How can I proceed in that case?

推荐答案

您要么必须模拟服务(在进行单元测试时总是一个好主意),要么使用如下所述的间谍程序.

You'll either have to mock your service, which is always a good idea when it comes to unit testing, or use a spy as explained below.

选项模拟:

...
providers: [
 {provide: PartService, useClass: MockPartService},
],
...

class MockPartService {
   list(): Observable<Part[]> {
   return Observable.of([...]);
}

您必须使用与测试中要调用的方法签名相同的方法签名来编写MockService.您可能需要将期望的返回值硬编码到此MockClass中.当您想要模拟时,通常就是您想要的东西. API请求等,因此您的测试不会抛出.

You'll have to write MockService with an identical method signature a the one you're calling within your test. You may want to hardcode your expected return value into this MockClass. This is usually what you want when you want to mock e.g. API requests etc. so your test doesn't throw.

选项间谍:

const mockParts: Part[] = [...]
const serviceSpy = spyOn(PartService, 'list').and.ReturnValue(Observable.of(mockParts));

在期望服务会为您带来特定回报的情况下使用此功能.

Use this when you expect a specific return by your service for your test.

您还可以在测试中自由组合. 存根spyOn(YourService, 'YourMethod').and.stub()只会阻止实际方法的调用,而不会返回任何值.

You're also free to mix both within your tests. A stub spyOn(YourService, 'YourMethod').and.stub() will just prevent the actual method from being called but will not return any value.

这篇关于在使用Jasmine进行单元测试时,我应该模拟或监视或存根注入到组件中的服务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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