gpt4 book ai didi

rxjs - Angular 6 单元测试 rxjs 6 操作符点击单元测试拦截器

转载 作者:行者123 更新时间:2023-12-03 14:57:09 25 4
gpt4 key购买 nike

由于我将代码更新为新的 Rxjs 6,因此我不得不像这样更改拦截器代码:

auth.interceptor.ts:

...
return next.handle(req).pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}),
catchError((error: any) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401) {
this.authService.loginRedirect();
}
return observableThrowError(this.handleError(error));
}
})
);

而且我无法测试 rxjs 运算符“tap”和“catchError”。

实际上我只能测试管道是否被调用:
it('should intercept and handle request', () => {
const req: any = {
clone: jasmine.createSpy('clone')
};

const next: any = {
handle: () => next,
pipe: () => next
};

spyOn(next, 'handle').and.callThrough();
spyOn(next, 'pipe').and.callThrough();

interceptor.intercept(req, next);

expect(next.handle).toHaveBeenCalled();
expect(next.pipe).toHaveBeenCalled();
expect(req.clone).toHaveBeenCalled();
});

关于如何监视 rxjs 运算符的任何帮助都值得赞赏

最佳答案

我认为问题在于您不应该首先测试运算符是否像这样被调用。

RxJS 5 和 RxJS 6 中的运算符都只是“制作配方”如何构造链的函数。这意味着检查是否 tapcatchError被调用并没有告诉你关于它的功能或链是否工作的任何信息(它可能会在任何值上抛出异常,你将无法测试它)。

由于您使用的是 RxJS 6,您应该通过发送值来测试链。这是有据可查的并且很容易做到https://github.com/ReactiveX/rxjs/blob/master/doc/marble-testing.md

在您的情况下,您可以执行以下操作:

const testScheduler = new TestScheduler((actual, expected) => {
// some how assert the two objects are equal
// e.g. with chai `expect(actual).deep.equal(expected)`
});

// This test will actually run *synchronously*
testScheduler.run(({ cold }) => {
const next = {
handle: () => cold('-a-b-c--------|'),
};
const output = interceptor.intercept(null, next);

const expected = ' ----------c---|'; // or whatever your interceptor does
expectObservable(output).toBe(expected);
});

我想你会明白这是做什么的......

关于rxjs - Angular 6 单元测试 rxjs 6 操作符点击单元测试拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50564066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com