Svelte Stores & Jest
Asked Answered
W

1

7

I'm looking for an way to mock/stub stores that are used in Svelte components, specifically with the auto-subscribe syntax (ie $myStore or $myStore.property).

I've tried a couple of different mocks, mostly along the lines of the following:

jest.mock('./stores/users', () => ({
  currentUser: jest.fn().mockImplementation(() =>
    writable({
      isAdmin: true,
    }),
  ),
}));

The test will error out on any auto-subscribed references to the store, which are undefined. For example, if I am referencing a store from "../../stores/users" in my component like so...

{#if $user.isAdmin}
  <div>Hello I'm an admin</div>
{/if}

... then I receive TypeError: Cannot read property 'isAdmin' of undefined

It seems that even when mocking a Svelte store, the $ auto-subscribe syntax is not breaking the test. I should point out that when logging the mocked store, the expected Svelte store methods (subscribe(), set() and update()) are there, and executing the subscribe() method exposes the isAdmin attribute also as expected.

I can't seem to find any established unit testing patterns that deal with Svelte and the use of stores, so any and all input on the topic would be greatly appreciated!

Whisk answered 20/11, 2021 at 0:15 Comment(1)
I'm running into a similar issue, only I'm trying to assign a value rather than read it ($sequence.events = sequenceEvents;). Everything works fine if I use the longer format (sequence.update(…)).Incurrent
D
0

The $ shortcut is unique to svelte. You cannot access it outside of a svelte application.

However, you can achieve the same thing using the get function exported from svelte/store, which will subscribe, read and immediately unsubscribe just like the $ shortcut you're wanting to use:

import { get } from 'svelte/store'
import store from './stores/users' //- change to your path

const user = get(store)
expect(user.isAdmin).toEqual(true)
Dearden answered 6/3, 2023 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.