I'm new to svelte and I'm wondering how to correctly mock the svelte/store with predefined state.
I've got this kind of approach and it's actually working, but I'm not sure if this is good way to do this.
This is my example.svelte
<script lang="ts">
import { userIds } from './store'
function storeHandler(ids: Set<string>) {
// some logic with the store values
return ids
}
$: result = storeHandler($userIds)
</script>
{#each result as item}
some funky stuff
{/each}
store.ts
import { writable } from 'svelte/store'
export const userIds = writable<Set<string>>(new Set())
And finally my example.test.ts :
it('some test case', async () => {
userIds.set(['612e8978c1af93207fc97808'])
render(Example)
//some test actions that are actually passing correctly
userIds.set([])
})
P.S the question is more of mocking the store that is not passed to components as a prop, but just imported directly inside.
After finding a solution, I'm starting to think that it might not be the best to mock your stores, when they're more complicated than just a basic
writeable, like mine.I expose an
initStorefunction from my stores, and I think that should be mocked, and the rest shouldn't be mocked.My stores can be found in the
$libfolder.@mockspoint to a general mock folder (__mocks__), and inside it I mocked thecategoriesstore, to be used in various test files.Here is an option to mock only the initialization:
For this solution, you would have to add the following alias to your
vitest.config.ts:Anyway, here is my solution to mock a whole store:
One way to do it is thus:
According to
vitest'smock's documentation, having the mock inside__mocks__and callingvi.mock('$lib/categories');inside your test file should call the mock, but it's not working for$lib.One way to solve it more globally, is defining your
vitest.config.tsthus:Then, export your stores from the
index.tsfile.BTW, I added my aliases for Svelte's
$app, I thought it might be useful as well (took me a while to nail that down).