如何为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(); }); });
关键说明
- 模拟document.cookie:由于
document.cookie是特殊属性,直接赋值无效,通过Object.defineProperty模拟可写的cookie属性,用于构造不同长度的Cookie测试场景。 - 监听Cookie操作:使用
spyOnProperty监听document.cookie的赋值行为,验证清理逻辑是否触发以及触发的正确性。 - 过期格式验证:确保每个被清除的Cookie都被设置了当前UTC时间的过期标记和根路径,保证Cookie能被彻底清除。
内容的提问来源于stack exchange,提问作者SGR
相关产品推荐
相关产品推荐

