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

pnpm运行Jest单元测试报错:TypeError: Cannot redefine property

pnpm替代npm后Jest单元测试报错:Cannot redefine property

最近将项目包管理器从npm替换为pnpm后,执行pnpm test命令时,单元测试抛出了npm test不会出现的错误。

测试代码如下:

import * as Test from '@/testfile/test'

describe('some ut', () => {
  test('test', () => {
     jest
      .spyOn(Test, 'someTest')
      .mockReturnValue({ returnValue: true });
  })
})

报错信息:

TypeError: Cannot redefine property:'someTest'
        at Function.defineProperty (<anonymous>)

尝试了三种解决方案但均无效:

方案1:

import { someTest } from '@/testfile/test'

describe('some ut', () => {
  test('test', () => {
     const Test = { someTest }
     jest
      .spyOn(Test, 'someTest')
      .mockReturnValue({ returnValue: true });
  })
})

方案2:

describe('some ut', () => {
  test('test', () => {
     jest.mock('@/testfile/test', () => {
       someTest: jest.fn().mockReturnValue({ returnValue: true })
     })
  })
})

方案3:参考了关于Jest spyOn在索引文件无法工作、无法重定义属性的相关解决方案,但未解决问题。

目前不清楚npm与pnpm的差异为何会引发该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:53:16