user7487097
user7487097

Reputation:

running Jest tests with webpack configuration

I am using next-optimized-images package to optimize my images in my next.js project.

This is a config that's supposed to enable me to load images and resize them automatically using URL params such as ?sizes[]=300

What works

next.config.js

const withOptimizedImages = require("next-optimized-images");

module.exports = withOptimizedImages({
  optimizeImagesInDev: true,
  module: {
    rules: [
      {
        test: /\.(jpe?g|png)$/i,
        loader: "responsive-loader",
        options: {
          adapter: require("responsive-loader/sharp"),
        },
      },
    ],
  },
});

I am also using png and jpg optimizing libraries:

"imagemin-mozjpeg": "^8.0.0","imagemin-optipng": "^6.0.0"

My JSON/JS files have their images structured in a following way:

{
  ...,
  imgs: [
    require("../../static/img/foo/bar.jpg?sizes[]=200,sizes[]=300"),
    ...,
  ]
}

so that when using it with responsive-loader everything is loaded as it should, i.e. images' paths are replaced with an object in the app that contains two paths with different sizes.

What does not work

What does not work, however, are the tests (jest tests) that used to work before I introduced the require declaration in each image array element. All it says is that it cannot import the required module because, most likely, it does not use the webpack configuration that would resolve those paths with arguments. How do I tell it to do that?

Error message:

Cannot find module '../../static/img/foo/bar.jpg?sizes[]=200,sizes[]=300' from 'categories.js'

I cannot simply use paths to images and then require them later in <img src={require(path)} /> tags, because they have to be relative for this library to work and I'm using those images in many different components (some are nested). With this library, the webpack configuration gets very difficult when it comes to absolute paths and also paths with arguments like size do not get resolved.

Upvotes: 1

Views: 2760

Answers (1)

user7487097
user7487097

Reputation:

Figured it out. All you have to do is create a config file for jest.

In your package.json change "test" from react-scripts test to jest -c jest.config.js

jest.config.js

{
  "bail": true,
  "verbose": true,

  "moduleNameMapper": {
    "^.*(jpe?g|png).*$": "<rootDir>/assetsTransformer.js"
  }
}

It's important to use moduleNameMapper to match against any image extension you need. Create another file named assetsTransformer.js which will process your required images. You don't actually have to do anything with imported images if you don't need to. In my case I did not so I just created a file with the following contents:

assetsTransformer.js

module.exports = {
  process(src, filename, config, options) {
    return;
  },
};

Upvotes: 6

Related Questions