womcauliff
womcauliff

Reputation: 101

How do I resolve Jest Mock error "Cannot find module"

Jest is throwing an error stating it cannot find the module specified by path in jest.mock()


> jest


 FAIL  test/userSelect.test.ts
  ● Test suite failed to run

Cannot find module '../src/actions/selectUserById' from 'test/userSelect.test.ts'


       8 | 
       9 | jest.mock('mysql');
    > 10 | jest.mock('../src/actions/selectUserById');
      11 | 
      12 | const mockSelectUserById = selectUserById as jest.MockedFunction<
      13 |   typeof selectUserById

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:306:11)
00:00
      at Object.mock (test/userSelect.test.ts:10:6)

The strangest part is this: this test passes on my local machine, but it fails in the CI service we are using.

Upvotes: 3

Views: 6584

Answers (2)

Daniel Viglione
Daniel Viglione

Reputation: 9507

In my case, instead of doing this:

const Client = require('./client');
jest.mock('Client');

I had to do this:

const Client = require('./client');
jest.mock('./client');

The reason why I tried the first way first is because in their example docs, they pass the axios object as a string to jest.mock, so I assumed I could pass in my own object as a string. Although in my implementation Client is exported with module.exports.

Upvotes: 1

womcauliff
womcauliff

Reputation: 101

In case anyone else is troubleshooting a similar issue, I finally realized the root-cause of the failing test was a difference in case-sensitivity of the specified path.

In my case the true filename is src/actions/selectUserByID (notice the uppercase letter 'D'), but the string I passed to Jest.mock() is selectUserById.

At some point, I renamed the file locally, which is why the test passes as expected on my machine. However, I learned a case-sensitive change to a filename is not detected as a change by git, which is why the CI service still had the erroneous filename.

I used git mv to commit the case-sensitive filename, and this resolved my issue.

Upvotes: 4

Related Questions