Trying to test a component containing a createResource

Hi! I have a component that shows some content I fetch using createResource. I wrapped the JSX in a <Suspense>, also tried with <Show when={myResource()}>, which works in the app. But when I try to test the component, it seems like myResource() is undefined, even though I mocked my fetcher and made it return Promise.resolve(someMockData). With <Show>, the data was just never showed. And with <Suspense>, I had errors saying that the data I wanted to display was undefined (myResource().someAttribute for example). I don't know if I explained well. I could provide some more information, but I wanted to know first if anyone already had this kind of issue trying to test a component using createResource. (using vitest)
6 Replies
nzdeep
nzdeep12mo ago
On the first pass (actually the only pass) resource be will Pending state initially in this case, it won't have executed the fetcher yet even if it is Promise.resolve for the data fetcher - https://playground.solidjs.com/anonymous/7c5e999e-36f5-444f-a1ea-5ab7c6311511
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
nzdeep
nzdeep12mo ago
So accessing resource().x will throw an exception access property on undefined - you'll see this in the console window This is basically as expected, you need to grok the idea that components only run once to setup all the reactivity tracking, and the unlike react suspense doesn't work by throwing promises, and chaining on them and re-running. So you need to guard around resource() being undefined. before access properties of the eventual value
Alex Lohr
Alex Lohr12mo ago
I wrote testEffect in @solidjs/testing-library to simplify testing resources.
Alex Lohr
Alex Lohr12mo ago
GitHub
solid-primitives/packages/resource/test/index.test.ts at main · sol...
A library of high-quality primitives that extend SolidJS reactivity. - solid-primitives/packages/resource/test/index.test.ts at main · solidjs-community/solid-primitives
Nyantastic
Nyantastic12mo ago
Thank you so much for your elaborate responses and for your time! Sorry I didn't see before. I understand better now, and yes I definitely should have paid attention to the resource being undefined. I'm gonna try all this! Thanks again!
Alex Lohr
Alex Lohr12mo ago
Happy to help. Testing is my topic, so I'm trying to make the DX for testing as smooth as possible. Questions like yours are helpful for me so I can identify our shortcomings and correct them. In this case, our documentation is still lacking, but I intend to resolve that.