Handle webpack loader syntax with Jest testing: exclamation raw-loader

Viewed 1373

My React project works great. Some files need the raw-loader and I don't want to eject the project. So I have some raw-loader imports like this:

import blank_md from '!!raw-loader!./assets/blank.md.txt';

But jest dies with an error

Cannot find module '!!raw-loader!./assets/blank.md.txt' from ...

This is similar to Jest issue 4868

After adding jest-raw-loader I tried adding to Jest's config:

"transform": { "^!!raw-loader!.*": "jest-raw-loader" }

but no dice.

Using mocking would be fine too.

3 Answers
 moduleNameMapper: {
   
    "^!!raw-loader!.*": "jest-raw-loader",
} 

This should load all the raw-loader import as required by jest.

Was looking for a solution myself and found that you should add the following module name mapping:

"moduleNameMapper": {
    "^!!raw-loader!./assets/(.*)$": "<rootDir>/src/[insert path]/assets/$1"
}

Replacing with your correct path for the assets directory.

Edit: A nicer approach is just doing this tho

"moduleNameMapper": {
    "^!!raw-loader!(.*)$": "$1"
}

I was able to use the Jest moduleNameMapper option to have Jest "use" the mock files.

The good news is that the Jest tests now run.

The bad news is that Jest still doesn't know how to load the files, so it supplies the filename to the app (instead of the file's contents). That's ok for my tests but is not optimal.

Here are some of the working settings that I'm using. I'm setting them in the package.json file:

"jest": {
  "setupFiles": ["<rootDir>/src/tests/setup-register-context.js"], 
  "moduleNameMapper": {
    "^!!raw-loader!.*sdkExamples.*txt": "<rootDir>/src/tests/__mocks__/templateMock.txt",
    "^!!raw-loader!\\./toolbox.xml": "<rootDir>/src/tests/__mocks__/xmlMock.xml",
    "^!!raw-loader!.*/assets/startBlocks.xml": "<rootDir>/src/tests/__mocks__/xmlMock.xml",
    "!!raw-loader!.*md\\.txt": "<rootDir>/src/tests/__mocks__/mdMock.md"
  }
}
Related