Search code examples
javascriptunit-testingjestjsvuejs3

Vue 3 Pina trying to test a pina store that has a dependency on another store


I basically have a store that depends on another store and I don't see a way to only mock the dependent store. example pseudo code vue 3 ish:

// the store I want to mock
export const useStore1 = defineStore({
    id: 'store1',
    state: (): State => ({
  
        someName:'blarg', // I know this is static but lets pretend it can change.
    }),
    // getter I want to mock
    getters: {
        name: (state) => state.someName,
    }
}

// store I want to test

export const useStoreTwo = defineStore({
    id: 'store2',
    state: (): State => ({
  
       someValue:'bar'
    }),
    getters: {
        value: (state) => {
        const store1 = useStore1() // dependency here
        return `${store1.name} state.someValue`
        },
    }
}


test
it('should return something' () => {
      //**** 
         someplace I would mock useStateOne and have it return
         a stub store with the getter name that returns 'foo'
      ***//
      const store2 = useStoreTwo();
      expect(store2.value).toBe('foo bar');
})


Solution

  • It is helpful to you.

    https://pinia.vuejs.org/cookbook/testing.html#mocking-getters

    By default, any getter will be computed like regular usage but you can manually force a value by setting the getter to anything you want

    import { createTestingPinia } from '@pinia/testing';
    
    const pinia = createTestingPinia()
        
    it('should return something' () => {
       const store1 = useStore1(pinia);
       store1.name = "foobar";
        
       const store2 = useStoreTwo();
       expect(store2.value).toBe('foobar');
    })