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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With