jest spyOn not working, TypeError: Cannot redefine property:XXX at Function.defineProperty (<anonymous>)

2.2k views Asked by At

Recently, I have used pnpm instead of npm in the program. When I use the script pnpm test, unit test throw errors which don't happen when I use npm test. All error codes like follow codes

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

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

and all errors like this

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

And I tried some solutions and workaround but these solutions don't work.

Solution 1:

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

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

Solution 2:

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

Solution 3: jest spyOn not working on index file, cannot redefine property

And I don't know what difference between npm and pnpm.

1

There are 1 answers

0
Anthony Wang On

compare the previous version and find out the lib version(@jest/console, @jest/core, @jest/environment, etc.) in node_modules has been changed. My jest version is 28.1.1. These lib's versions are 28.1.3. So I downgraded these versions and fixed the issue.