Jest exception "cannot find module" with spfx solutions

Sharma, Deepak 0 Reputation points

I have written some unit test cases to test my SPFx web part using Jest and Enzyme. However, when I ran the tests, I encountered a "Cannot find module" exception on the import statement.

See below error details -

Cannot find module './httpClient/HttpClient' from 'node_modules/@microsoft/sp-http/lib-commonjs/index.js'
  Require stack:

  at Resolver.resolveModule (node_modules/jest/node_modules/jest-resolve/build/resolver.js:324:11)
  at Object.<anonymous> (node_modules/@microsoft/sp-http/lib-commonjs/index.js:14:20)
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,890 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 32,246 Reputation points Microsoft Vendor

    Hi @Sharma, Deepak,

    Have you installed Jest and Enzyme? You can install them by following cmdlet

    npm install enzyme enzyme-adapter-react-16 react-test-renderer @types/enzyme --save-dev --save-exact
    npm install jest jest-junit ts-jest @types/jest --save-dev --save-exact  

    And also you will need to setup the jest with spfx, please check the following steps in the nice article

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.