【发布时间】:2018-01-11 14:18:28
【问题描述】:
我是单元测试的新手,想知道如何对依赖于一个服务的组件进行单元测试,而该组件又依赖于许多其他服务。下面是我的初始设置。
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestComp],
providers: [TestService]
}).compileComponents();
}));
但是这样做,它无法找到它所依赖的其他服务。然后我会像这样提供其他服务。但随着这些服务使用其他服务等,它会继续增长。
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestComp],
providers: [TestService, TestServiceDependencyService, TestServiceDependecyService2]
}).compileComponents();
}));
我对另一个依赖于服务的单元测试做的一件事是创建一个像这样的模拟服务。
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
}).overrideComponent(TestComponent, {
set: {
providers: [
{ provide: TestService, useClass: MockTestService},
]
}
})
.compileComponents();
}));
现在这里的模拟服务更容易了,因为没有太多功能,而且我能够“模拟”返回值。
在这个新组件中 - 模拟正确的返回值要困难得多。在这种情况下我该怎么办?
【问题讨论】:
-
是的,使用模拟服务。目前尚不清楚您当前组件的具体问题是什么;您实际上并没有表现出预期的行为,也没有在测试中尝试将其消除。
-
我会嘲笑什么?嘲笑所有服务似乎有点不对劲?现在没有嘲笑,只是提供服务,我得到一个 service.method() is not a function
-
“我要模拟什么?” - 您正在测试的服务所依赖的其他服务。 “模拟所有服务似乎有点不对劲?” - 这是一个问题吗?为什么这看起来不对?关键是您要隔离那个服务的行为。 “现在...” - 然后给minimal reproducible example。这个问题太模糊,无法正确回答,因此回答平庸。
标签: angular unit-testing jasmine