8

I am importing SVG's into my component and importing them as components using ReactComponent, for example

import { ReactComponent as D1 } from '../../../assets/images/characteristics/D1.svg';

When I run Jest/Enzyme to test the component, I get the following error

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Does it appear that I need to mock this? How could I do that?

4
  • 6
    so it's SVGR who loads SVG as React component, am I right? If I'm accurate here, it's a webpack loader. Did you try mocking svg through moduleNameMapper as their docs suggested? Commented Aug 20, 2020 at 20:47
  • Hi @skyboyer I believe it does use SVGR under the hood as i use create-react-app. Thanks, I will try this and report back Commented Aug 20, 2020 at 21:27
  • Hi @skyboyer,this works thanks Commented Aug 21, 2020 at 8:51
  • cool! could you please make a self-answer with bit of instructions? someone may find this by search and barely read comments, only looking for answers Commented Aug 21, 2020 at 9:56

2 Answers 2

13

Although the solution pointed out by @skyboyer worked for me, it showed the following error in the console when running the tests:

<SvgrURL /> is using incorrect casing. Use PascalCase for React components, 
or lowercase for HTML elements.

Changing to the following inside the mock file worked for me as a solution:

import React from 'react';
 
const SvgrMock = React.forwardRef((props, ref) => <span ref={ref} {...props} />);

export const ReactComponent = SvgrMock;
export default SvgrMock;

reference

Sign up to request clarification or add additional context in comments.

1 Comment

This is the perfect solution to mock svg files for @svgr/webpack 🍕
3
  1. Add a mock file for svg and put it in the __mocks__ folder
  2. Add a module name mapper inside jest config

__mocks__/svgMock.js

import React from 'react';
const SvgrMock = React.forwardRef((props, ref) => <span ref={ref} {...props} />);
export const ReactComponent = SvgrMock;
export default SvgrMock;

Jest.config.js

module.exports = {
    ...
    moduleNameMapper: {
        ...
        '\\.(svg)$': '<rootDir>/__mocks__/svgMock.js',
    },
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.