【发布时间】:2020-10-28 04:23:45
【问题描述】:
在测试 Angular 服务(具有自己的依赖项)时,我经常发现自己在测试套件中同时测试快乐路径和悲伤路径。
我的意思是我有这项服务:
export class MyService {
constructor(private MyClient) {}
public doIt() {
return this.myClient.doTheThing().pipe(
catchError(error => {
// error handling logic
}),
// process the response
)
}
}
现在我想测试MyService#doIt 当MyClient#doTheThing 成功运行并返回该请求的响应/结果的可观察值时,以及当MyClient#doTheThing 失败和错误时(因为我在@ 中有一些逻辑987654325@待测)。
测试幸福路径很简单:
// MyClientMock is a mock implementation of MyClient that returns a canned result
// for instance so that I can test against these values when running the tests.
describe(MyService, () => {
let service: MyService
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
MyService,
{ provide: MyClient, useClass: MyClientMock }
],
})
service = TestBed.inject(MyService)
})
it('does the thing', (done) => {
service.doIt().subscribe(result => {
expect(result).toEqual('something')
done()
})
})
})
但是当MyClient 抛出错误时,我如何测试悲伤路径,并确保catchError 中的逻辑符合我的预期?
我想过创建另一个MyClientMock 并将其命名为MyClientErrorMock,它将抛出。但是我不能注入它,因为它在测试开始时就已经设置好了,它会干扰其他测试用例。
在这种情况下使用什么模式来测试依赖项错误或成功时会发生什么?
【问题讨论】:
标签: angular unit-testing jestjs