poppa / sveltekit-svg

SvelteKit plugin that makes it possible to import SVG files as Svelte components, inline SVG code or urls
MIT License
235 stars 23 forks source link

How to use SVG component in Jest? #22

Closed pontakornth closed 2 years ago

pontakornth commented 2 years ago

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 />
pontakornth commented 2 years ago

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 2 years ago

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.

pontakornth commented 2 years ago

@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.