How to mock an image and path in JEST + webpack5 + React?

Viewed 235

I am trying to test a simple image component which is as follows:

const ImageComponent = (props) => {
    const fullPath = require(`assets/images/${props.src}`);
    return <img {...props} src={fullPath} alt={props.src} />;
};

and trying to test gives Error:

Error: Cannot find module 'assets/images/BigFakeImage' from 'test/components/common/ImageComponent.test.js'

test excerpt is as follows :

    const props = {
            src: 'BigFakeImage',
            className: 'class-name-image',
            alt: 'big picture'
        };
        const {result} = renderHook(() => ImageComponent(props), {
            wrapper: ({children}) => (
                <Provider store={store}>{children}</Provider>
            )
        });
        return result.current;
    };

    it('should render <img/> with defined props', () => {
        jest.mock('assets/images/BigFakeImage');
        const wrapper = setup();
        expect(wrapper).toMatchSnapshot();
    });

I also tried the "moduleNameMapper" settings as specified here : https://jestjs.io/docs/webpack

But it causes the test suite to fail.

what can be done to mock the fake image and path and for the test to pass? TIA.

0 Answers
Related