Mock Lerna scoped module with Jest

Viewed 327

I have a monorepo setup with Lerna. The project is compiled with tsc and the tests are ran with ts-jest v27.

One of the files that I'm trying to test has this code:

import { someFunction } from '@local/package/dist/something'

const someLogic = () => {
  someFunction()
}

@local/package is a local monorepo package symlinked by Lerna.

I need to mock someFunction.

Things I've tried:


jest.mock('@local/package/dist/something')

Has zero effect, the original file is still called.


import * as something from '@local/package/dist/something'

jest.spyOn(something, 'someFunction')

Zero effect.


import * as something from '@local/package/dist/something'
something.someFunction = jest
      .fn()
      .mockReturnValue(123)

Leads to TypeError: Cannot set property "someFunction" of #<Object> which has only a getter


jest.config.js:

{
moduleNameMapper: {
    '(.*)something(.*)': '<rootDir>/src/somethingMock.js',
  }
}

Zero effect.


I tried to create 'mocks/@local/package/dist/something.js' next to package.json of the package inside which I have tests.
Zero effect.


I'm tired and I need help.... What am I doing wrong?

1 Answers

These were end to end tests that trigger an HTTP endpoint, the code that I was trying to mock was running in a separate process lol.

Related