Jest exception "cannot find module" with spfx solutions

Sharma, Deepak 0 Reputation points
2023-05-12T10:57:22.0366667+00:00

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:
  node_modules/@microsoft/sp-http/lib-commonjs/index.js
  src/common/services/sp-services.ts
  src/webparts/TestWebpart/components/custom/Services.ts
  src/webparts/TestWebpart/components/TestWebpart.tsx
  src/webparts/TestWebpart/test/TestWebpart.test.tsx

  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)
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,624 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 31,071 Reputation points Microsoft Vendor
    2023-05-15T06:06:13.3466667+00:00

    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

    https://www.c-sharpcorner.com/article/spfx-unit-test-with-jest-and-enzyme/


    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.