poppa/sveltekit-svg

How to use SVG component in Jest?

pontakornth opened this issue · 3 comments

I am trying to setup Jest unit test but Jest cannot transform .svg file. I don't know how to do it when it is imported as a Svelte component.

import Exclamation from '$lib/icons/exclamation.svg'

<Exclamation />

I discovered a funny solution. I just need to map .svg to a Svelte component with an empty svg tag. Then, use moduleNameMapper.

jest.config.cjs

module.exports = {
// Unrelated config
	moduleNameMapper: {
		// Other config
		'^.+\\.svg$': '<rootDir>/src/lib/EmptyIcon.svelte'
	},
}

EmptyIcon.svelte

<svg />

I am not sure if I miss any edge case or something I should know so I don't close it for now.

poppa commented

Thanks for your feedback. I haven't used it with Jest myself so I can't give you any pointers. Byt this is good info to know and add to the the README file.

I will take a look at it when I get time and also update the README with info on testing framework integrations.

@poppa That's great. By the way, I discovered that ?url can be used with jest-transform-stub in both transform and moduleMapper. I am not sure which one fixed the issue but at least it works.