You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Angular拦截器的Cookie删除逻辑编写测试用例

针对Angular拦截器中Cookie清理逻辑的测试用例设计

测试目标

验证拦截器中Cookie清理逻辑的正确性:当document.cookie总长度超过4500时,自动清除所有Cookie;长度未超过时不执行任何清理操作。


测试用例与代码实现

使用Angular测试框架(Jasmine)编写以下测试用例:

import { TestBed } from '@angular/core/testing';
import { HttpErrorService } from './http-error.service';
import { HttpHandler, HttpRequest } from '@angular/common/http';

describe('HttpErrorService - Cookie Cleanup Logic', () => {
  let interceptor: HttpErrorService;
  let httpHandler: jasmine.SpyObj<HttpHandler>;

  beforeEach(() => {
    // 创建HttpHandler的模拟对象
    httpHandler = jasmine.createSpyObj('HttpHandler', ['handle']);
    
    TestBed.configureTestingModule({
      providers: [
        HttpErrorService,
        { provide: HttpHandler, useValue: httpHandler }
      ]
    });
    
    // 注入待测试的拦截器
    interceptor = TestBed.inject(HttpErrorService);
  });

  // 测试场景1:Cookie总长度超过4500时,执行全量清除
  it('clears all cookies when document.cookie length exceeds 4500', () => {
    // 构造长度超过4500的模拟Cookie字符串
    const longCookieContent = 'a=' + 'x'.repeat(4500) + '; b=test_cookie; c=another_cookie';
    Object.defineProperty(document, 'cookie', {
      value: longCookieContent,
      writable: true,
      configurable: true
    });

    // 监听document.cookie的赋值操作
    const cookieSetSpy = spyOnProperty(document, 'cookie', 'set');

    // 触发拦截器逻辑
    interceptor.intercept(new HttpRequest('GET', '/api/test'), httpHandler);

    // 验证清除操作次数等于Cookie项数量
    expect(cookieSetSpy).toHaveBeenCalledTimes(longCookieContent.split(';').length);
    
    // 验证每个Cookie都被设置为过期状态
    longCookieContent.split(';').forEach(rawCookie => {
      const expectedExpiredCookie = rawCookie.replace(/^ +/, '')
        .replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`);
      expect(cookieSetSpy).toHaveBeenCalledWith(expectedExpiredCookie);
    });
  });

  // 测试场景2:Cookie总长度未超过4500时,不执行清除
  it('does not clear cookies when document.cookie length is under 4500', () => {
    // 构造短Cookie字符串
    const shortCookieContent = 'a=demo; b=test';
    Object.defineProperty(document, 'cookie', {
      value: shortCookieContent,
      writable: true,
      configurable: true
    });

    // 监听document.cookie的赋值操作
    const cookieSetSpy = spyOnProperty(document, 'cookie', 'set');

    // 触发拦截器逻辑
    interceptor.intercept(new HttpRequest('GET', '/api/test'), httpHandler);

    // 验证未执行任何Cookie赋值操作
    expect(cookieSetSpy).not.toHaveBeenCalled();
  });
});

关键说明

  1. 模拟document.cookie:由于document.cookie是特殊属性,直接赋值无效,通过Object.defineProperty模拟可写的cookie属性,用于构造不同长度的Cookie测试场景。
  2. 监听Cookie操作:使用spyOnProperty监听document.cookie的赋值行为,验证清理逻辑是否触发以及触发的正确性。
  3. 过期格式验证:确保每个被清除的Cookie都被设置了当前UTC时间的过期标记和根路径,保证Cookie能被彻底清除。

内容的提问来源于stack exchange,提问作者SGR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 12:58:11