简体   繁体   中英

set absolute path for jest in react project

I have followed this document and set an absolute path across the project. But when I run test case it gives me following error

  Your application tried to access assets, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.

Required package: assets (via "assets\icons")
Required by: E:\Project\src\components\LayoutContainer\


Require stack:
  src/components/LayoutContainer/index.jsx
  src/components/LayoutContainer/__test__/index.spec.js

  27286 |     enumerable: false
  27287 |   };
> 27288 |   return Object.defineProperties(new Error(message), {
        |                                  ^
  27289 |     code: { ...propertySpec,
  27290 |       value: code
  27291 |     },

  at internalTools_makeError (.pnp.js:27288:34)
  at resolveToUnqualified (.pnp.js:28247:23)
  at resolveRequest (.pnp.js:28345:29)
  at Object.resolveRequest (.pnp.js:28423:26)

My Package.json for jest configuration is as follow

 "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}",
      "!src/components/**/*.{js,jsx}",
      "!<rootDir>/node_modules/",
      "!<rootDir>/path/to/dir/",
      "!src/**/*.css",
      "!src/setUpTests.js",
      "!src/index.jsx"
    ],
    "coverageThreshold": {
      "global": {
        "branches": 90,
        "functions": 90,
        "lines": 90,
        "statements": 90
      }
    },
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  },

I tried to follow many open solutions. But none are working for me

My jsonconfig.json file

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

I added the following configuration as part of craco file and worked for me

module.exports = {
  jest: {
    configure: {
      moduleNameMapper: {
        // Jest module mapper which will detect our absolute imports.
        '^assets(.*)$': '<rootDir>/src/assets$1',
        '^pages(.*)$': '<rootDir>/src/pages$1',
        '^config(.*)$': '<rootDir>/src/config$1',
        '^navigation(.*)$': '<rootDir>/src/navigation$1',
        '^utils(.*)$': '<rootDir>/src/utils$1',
        '^components(.*)$': '<rootDir>/src/components$1',
        '^services(.*)$': '<rootDir>/src/services$1',

        // Another example for using a wildcard character
        '^~(.*)$': '<rootDir>/src$1'
      }
    }
  }
}

reference - https://resir014.xyz/posts/2019/03/13/using-typescript-absolute-paths-in-cra-20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM