角 - 测试简单拦截器

发布于 2025-02-05 08:44:06 字数 2348 浏览 4 评论 0原文

我尝试了如此努力,但是对于这样的简单拦截器,我似乎无法弄清楚如何正确创建Spec.ts文件(为了拥有100%的代码覆盖范围):

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private errorService: ErrorService, private cookieService: CookieService) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    // Handle cookies
    request = request.clone({
      headers: new HttpHeaders({
        'X-Csrf-Token': this.cookieService.get(Constants.COOKIES_KEYS.DTM_CSRF_TOKEN),
        SessionId: this.cookieService.get(Constants.COOKIES_KEYS.DTM_SESSION_ID)
      })
    });
    return next.handle(request);
  }
}

这是我已经达到的一点到目前为止:

describe('AuthInterceptor', () => {
  let interceptor: AuthInterceptor;
  let cookieService: CookieService;

  beforeEach(() =>
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientTestingModule],
      providers: [AuthInterceptor]
    })
  );

  beforeEach(() => {
    interceptor = TestBed.inject(AuthInterceptor);
    cookieService = TestBed.inject(CookieService);
  });

  it('should be created', () => {
    expect(interceptor).toBeTruthy();
  });

  it(
    'should replace request headers',
    waitForAsync(() => {
      const endpoint = `${environment.apiHost}/${environment.apiUrl}/v1/user`;
      const mockReq = new HttpRequest('GET', endpoint);
      const next: HttpHandler = {
        handle: () => {
          return new Observable<HttpEvent<any>>(subscriber => {
            subscriber.complete();
          });
        }
      };
      const cookieServiceGetSpy = spyOn(cookieService, 'get');
      cookieServiceGetSpy.withArgs(Constants.COOKIES_KEYS.DTM_CSRF_TOKEN).and.returnValue('testToken');
      cookieServiceGetSpy.withArgs(Constants.COOKIES_KEYS.DTM_SESSION_ID).and.returnValue('testSessionId');
      interceptor.intercept(mockReq, next).subscribe(response => {
        expect(response).toBeTruthy();
        expect(mockReq.headers.get('X-Csrf-Token')).toBe('testToken');
        expect(mockReq.headers.get('SessionId')).toBe('testSessionId');
      });
    })
  );
});

我的主要问题是在执行“截距”订阅后没有触发“期望”呼叫(第一个场景Wihtouth waitforasync'子句),当在“ waitforasync”条款中插入时,业力也没有识别。

您会介意显示这样的最基本拦截器的最正确方法吗?

先感谢您。

I tried so hard, but it seems like I can't figure out how to correctly create the spec.ts file (in order to have a 100% code coverage) for a simple interceptor like this:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private errorService: ErrorService, private cookieService: CookieService) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    // Handle cookies
    request = request.clone({
      headers: new HttpHeaders({
        'X-Csrf-Token': this.cookieService.get(Constants.COOKIES_KEYS.DTM_CSRF_TOKEN),
        SessionId: this.cookieService.get(Constants.COOKIES_KEYS.DTM_SESSION_ID)
      })
    });
    return next.handle(request);
  }
}

This is the point that I have reached so far:

describe('AuthInterceptor', () => {
  let interceptor: AuthInterceptor;
  let cookieService: CookieService;

  beforeEach(() =>
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientTestingModule],
      providers: [AuthInterceptor]
    })
  );

  beforeEach(() => {
    interceptor = TestBed.inject(AuthInterceptor);
    cookieService = TestBed.inject(CookieService);
  });

  it('should be created', () => {
    expect(interceptor).toBeTruthy();
  });

  it(
    'should replace request headers',
    waitForAsync(() => {
      const endpoint = `${environment.apiHost}/${environment.apiUrl}/v1/user`;
      const mockReq = new HttpRequest('GET', endpoint);
      const next: HttpHandler = {
        handle: () => {
          return new Observable<HttpEvent<any>>(subscriber => {
            subscriber.complete();
          });
        }
      };
      const cookieServiceGetSpy = spyOn(cookieService, 'get');
      cookieServiceGetSpy.withArgs(Constants.COOKIES_KEYS.DTM_CSRF_TOKEN).and.returnValue('testToken');
      cookieServiceGetSpy.withArgs(Constants.COOKIES_KEYS.DTM_SESSION_ID).and.returnValue('testSessionId');
      interceptor.intercept(mockReq, next).subscribe(response => {
        expect(response).toBeTruthy();
        expect(mockReq.headers.get('X-Csrf-Token')).toBe('testToken');
        expect(mockReq.headers.get('SessionId')).toBe('testSessionId');
      });
    })
  );
});

My main problem is that "expect" calls are not triggered after the "intercept" subscription is performed (first scenario wihtouth the "waitForAsync" clause), nor are recognized by Karma when inserted inside a "waitForAsync" clause.

Would you mind showing the most correct way to test a very basic interceptor like this?

Thank you in advance.

A.M.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酷炫老祖宗 2025-02-12 08:44:06

我设法通过调整Spec.TS文件来解决此问题:

describe('AuthInterceptor', () => {
  let interceptor: AuthInterceptor;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientTestingModule],
      providers: [AuthInterceptor]
    });
    interceptor = TestBed.inject(AuthInterceptor);
  });

  it('should be created', () => {
    expect(interceptor).toBeTruthy();
  });

  it('should replace request headers', done => {
    const mockReq = new HttpRequest('GET', '/test');
    const requestCloneSpy = spyOn(mockReq, 'clone');
    const next: any = {
      handle: () => {
        return of({ status: ApiResponseStatus.OK } as ApiResponse);
      }
    };
    interceptor.intercept(mockReq, next).subscribe(() => {
      expect(requestCloneSpy).toHaveBeenCalled();
      done();
    });
  });
});

I manage to solve this issue by adjusting the spec.ts file as follows:

describe('AuthInterceptor', () => {
  let interceptor: AuthInterceptor;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientTestingModule],
      providers: [AuthInterceptor]
    });
    interceptor = TestBed.inject(AuthInterceptor);
  });

  it('should be created', () => {
    expect(interceptor).toBeTruthy();
  });

  it('should replace request headers', done => {
    const mockReq = new HttpRequest('GET', '/test');
    const requestCloneSpy = spyOn(mockReq, 'clone');
    const next: any = {
      handle: () => {
        return of({ status: ApiResponseStatus.OK } as ApiResponse);
      }
    };
    interceptor.intercept(mockReq, next).subscribe(() => {
      expect(requestCloneSpy).toHaveBeenCalled();
      done();
    });
  });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文