How do I mock a store in Vitest? #9759
-
I'm trying to write a component test for a LoginLogout component, which depends on the The component has this (login/logout buttons removed for clarity:) {#if $isAnonymous}
Logged out
{:else}
<span class="username" data-testid="currently-logged-in-user">
Logged in as {$user.username}
</span>
{/if} I can test the "user is logged out" case just fine, because it's the default — but how do I mock the store for the "user is logged in" case, such that I've tried testing a wrapper component, based on #1485 (comment), but I can't get it to work — the user still shows as logged out. <script lang="ts">
import { setContext } from 'svelte'
import * as userStore from '$stores/user'
import { readable } from 'svelte/store'
import LoginLogout from './LoginLogout.svelte'
export let isAnonymous = true
export let user = {
email: '[email protected]',
id: 'userid',
userLevel: 'admin',
username: 'user'
}
const store = {
...userStore,
isAnonymous: readable(isAnonymous),
user: readable(user),
}
setContext('__svelte__', {
user: store,
})
</script>
<LoginLogout /> I can't find a documented way of doing this, but surely it must be possible. I don't want to have to mock the API calls that are made to log in and get the current user, as that means the component test is effectively testing the store as well as the thing it's supposed to be testing — mocking the store so it returns the correct values for the context is the cleanest way of doing this. (I'm also not 100% sure that mocking the API calls will work either…) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
We are mocking all of our stores, too. We use the same pattern for every store. We would mock a boolean File: mock-store.ts import { writable } from 'svelte/store';
const mockIsAnonymousWritable = writable<boolean>();
export const mockIsAnonymousStore = {
subscribe: mockIsAnonymousWritable.subscribe,
set: vi.fn(), // add as much store functions you need here and set them to vi.fn(), so you can call expect() functions on them
mockSetSubscribeValue: (value: boolean): void => mockIsAnonymousWritable.set(value)
}; In the test now you can just mock the real store with the mockStore. With |
Beta Was this translation helpful? Give feedback.
-
Thanks — but both What would I put in the test so that, when the component calls |
Beta Was this translation helpful? Give feedback.
We are mocking all of our stores, too. We use the same pattern for every store.
We would mock a boolean
$isAnonymous
store this way:File: mock-store.ts
In the test now you can just mock the real store with the mockStore. With
mockIsAnonymousStore.mockSetSubscribeValue(...)
you can set the value …