Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest snapshots for react native static images throwing warnings

I am trying to write snapshots tests to check if the correct image is being returned. When I just use zero transforms than the result is always '1' which isnt very helpful. I went onto the site and added this to my package.json

"transform": {
  "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/jest/fileTransformer.js"
}

and create a file called fileTransformer that looks like this

    // fileTransformer.js
const path = require('path');

module.exports = {
  process(src, filename, config, options) {
    return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
  },
};

Now the tests are resulting in useful snapshots which is great, however im not getting warnings in my console that look like this

console.error node_modules/prop-types/checkPropTypes.js:20
      Warning: Failed prop type: Invalid prop `source` supplied to `Image`.
          in Image
like image 905
Adam Katz Avatar asked Sep 17 '25 08:09

Adam Katz


1 Answers

You can take a look at moduleNameMapper configuration

"^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",

and inside the file you can export a dummy image path

RelativeImageStub.js
export default '/dummy/path/to/dummyImage.png';

You should also be able to mock the result from importing the image:

Component.spec.js
import Component from './Component';

jest.mock('./path/to/the/image.png', () => "dummy/path/image.png");
Component.js
import image from './path/to/the/image.png';

export default function Component() {
  return <Image source={image} />;
}

This way you'll also get an error if the specified path does not exists.

like image 147
Teneff Avatar answered Sep 21 '25 10:09

Teneff