enzyme: An InvalidCharacterError when mounting a component using an svg
I have a component which uses the following svg file:
delete.svg
<svg xmlns="http://www.w3.org/2000/svg" width="28" height="32" viewBox="0 0 28 32">
<path fill="#95A6B8" fill-rule="evenodd" ... />
</svg>
MyComponent.js
import DeleteIcon from "./delete.svg";
import style from "./MyComponent.scss";
class MyComponent extends Component {
removeItemFromList(item, event) {
//...
}
render() {
return <div>
<DeleteIcon
className={style.removeButton}
onClick={this.removeItemFromList.bind(this, item)}
/>
<div>
}
export default MyComponent;
MyComponent.test.js
describe("editable", function() {
let componentWrapper;
beforeEach(() => {
componentWrapper = mount(
<MyComponent
data={[]}
/>
);
});
afterEach(() => {
componentWrapper.unmount();
});
it("testing something...", () => {
expect(componentWrapper.exists(".someClass")).toEqual(true);
});
})
Current behavior
When mounting, I get the following InvalidCharacterError error:
InvalidCharacterError: "" did not match the Name production: Unexpected syntax in top
Line 1:
^^^
at exports.name (/node_modules/jsdom/lib/jsdom/living/helpers/validate-names.js:11:11)
at DocumentImpl.createElement (/node_modules/jsdom/lib/jsdom/living/nodes/Document-impl.js:688:5)
at Document.createElement (/node_modules/jsdom/lib/jsdom/living/generated/Document.js:134:45)
at createElement (/node_modules/react-dom/cjs/react-dom.development.js:7630:34)
at createInstance (/node_modules/react-dom/cjs/react-dom.development.js:8714:20)
Expected behavior
Mounting is successful. Using shallow this error isn’t thrown.
Your environment
API
- shallow
- mount
- render
Version
| library | version |
|---|---|
| enzyme | 3.8.0 |
| react | 16.7.0 |
| jest | 23.6.0 |
Adapter
- enzyme-adapter-react-16
- enzyme-adapter-react-16.3
- enzyme-adapter-react-16.2
- enzyme-adapter-react-16.1
- enzyme-adapter-react-15
- enzyme-adapter-react-15.4
- enzyme-adapter-react-14
- enzyme-adapter-react-13
- enzyme-adapter-react-helper
- others ( )
I’ve seen issue #1510 but it’s really the same error…
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Comments: 15 (7 by maintainers)
OK, I managed to solve it using a babel plugin:
babel-plugin-inline-react-svgThanks for the help!react-svg-loaderwill only work in webpack - you need to have a way for it to work in node.You may want to try using https://www.npmjs.com/package/babel-plugin-inline-react-svg for non-browser builds.
Note that importing scss, css, etc - basically anything that’s not
.js,.node, or.json- needs to have babel transforms NOT webpack config, to be able to have it work in tests (any tests, not just enzyme).In general, very little should be in your webpack config, and it should all be done with babel transforms instead.
Also, I failed to mention in my case, I am not importing any
svgs. It’s failing on a simple component mount with that same error.