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

使用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初始化逻辑需要调整。

可行方案

  1. 改用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");
    })
    
  2. 直接覆写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");
    })
    
  3. 清理mock避免污染
    无论用哪种方式,建议在测试后清理mock,防止影响其他测试用例:

    afterEach(() => {
      jest.clearAllMocks();
      // 如果用了覆写方式,可恢复原方法
      delete localStorage.getItem;
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:55:21