使用Jest与Angular(NX)时遇TypeError: spy.mockReturnValue不是函数问题
问题
我编写了如下Angular测试用例:
it('should display user email', () => { const header = fixture.debugElement; const spy = jest.spyOn(localStorage, 'getItem'); spy.mockReturnValue('test@test.com'); fixture.detectChanges(); expect(header.query(By.css(".user-label")).nativeElement.innerText).toContain("test@test.com"); })
运行时抛出错误:TypeError: spy.mockReturnValue is not a function
环境信息:NX 14.5.2(内置Jest 27.5.1、Angular 14.0.2)
解决办法
原因分析
这个错误通常是因为jest.spyOn针对原生API(比如localStorage.getItem)创建的spy对象,在部分场景下无法直接调用mockReturnValue,或是Jest的mock初始化逻辑需要调整。
可行方案
改用
mockImplementation
替换mockReturnValue为mockImplementation,显式定义方法的返回逻辑:it('should display user email', () => { const header = fixture.debugElement; const spy = jest.spyOn(localStorage, 'getItem'); // 替换为mockImplementation spy.mockImplementation(() => 'test@test.com'); fixture.detectChanges(); expect(header.query(By.css(".user-label")).nativeElement.innerText).toContain("test@test.com"); })直接覆写
localStorage.getItem
如果spyOn方式仍有问题,可以直接修改localStorage的属性实现:it('should display user email', () => { const header = fixture.debugElement; // 覆写getItem方法 Object.defineProperty(localStorage, 'getItem', { value: jest.fn(() => 'test@test.com'), writable: true }); fixture.detectChanges(); expect(header.query(By.css(".user-label")).nativeElement.innerText).toContain("test@test.com"); })清理mock避免污染
无论用哪种方式,建议在测试后清理mock,防止影响其他测试用例:afterEach(() => { jest.clearAllMocks(); // 如果用了覆写方式,可恢复原方法 delete localStorage.getItem; });
内容的提问来源于stack exchange,提问作者Misko Jones
相关产品推荐
相关产品推荐

