Testing createResource with dynamic import

I'm trying to test an Icon component that I built that uses a dynamic import inside of a createResource. I attempted to mock createResource but couldn't get it to work as expected... I'll just post a simplified version of the component in the hopes that someone knows based off of the code. And FWIW I'm using vite-plugin-solid-svg to import svg files as solid components. Also, I was prompted to try to do this because I can run tests to get 100% coverage on statements, branches, and lines... but my function coverage was like 3%. It seems to be related to the dynamic import so perhaps I'm barking up the wrong tree with createResource?
import { createResource, Show } from "solid-js";

export function Icon(props) {
const [lazyIcon] = createResource(
() => props.icon,
async (iconName) => {
try {
const lazyFile = await import(`./icons/icon-${iconName}.svg?component-solid`);
return lazyFile.default;
} catch {
return null;
}
}
);

return (
<Show when={lazyIcon()} fallback={<div />}>
{(LoadedIcon) => (
<div id={props.id}}>
{LoadedIcon()}
</div>
)}
</Show>
);
}
import { createResource, Show } from "solid-js";

export function Icon(props) {
const [lazyIcon] = createResource(
() => props.icon,
async (iconName) => {
try {
const lazyFile = await import(`./icons/icon-${iconName}.svg?component-solid`);
return lazyFile.default;
} catch {
return null;
}
}
);

return (
<Show when={lazyIcon()} fallback={<div />}>
{(LoadedIcon) => (
<div id={props.id}}>
{LoadedIcon()}
</div>
)}
</Show>
);
}
1 Reply
flippyflops
flippyflopsOP4mo ago
I ended up solving this but decided to ultimately just ignore the dynamic import testing. If anyone is curious about the implementation I had to test 100% here is what I had:
describe("<Icon />", () => {
// concurrentIcons = import.meta.glob('./icons/*.svg) ... some mapping and filtering to get proper icon names
for (const iconName of concurrentIcons) {
test(
`renders <Icon icon="${iconName}" />`,
{ retry: 5, concurrent: true },
async ({ expect: localExpect }) => {
const id = `test-${iconName}`;
const { container, unmount } = render(() => (
<Icon icon={iconName as IconType} id={id} />
));
await waitFor(() => {
localExpect(container.querySelector(`#${id}`)).toBeInTheDocument();
unmount();
});
}
);
}
});
describe("<Icon />", () => {
// concurrentIcons = import.meta.glob('./icons/*.svg) ... some mapping and filtering to get proper icon names
for (const iconName of concurrentIcons) {
test(
`renders <Icon icon="${iconName}" />`,
{ retry: 5, concurrent: true },
async ({ expect: localExpect }) => {
const id = `test-${iconName}`;
const { container, unmount } = render(() => (
<Icon icon={iconName as IconType} id={id} />
));
await waitFor(() => {
localExpect(container.querySelector(`#${id}`)).toBeInTheDocument();
unmount();
});
}
);
}
});
Want results from more Discord servers?
Add your server