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

Viewed 1083

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.

1 Answers

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.

Related