Reputation: 1709
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');
})
Upvotes: 2
Views: 3459
Reputation: 356
I have solved this issue by mocking the imported useStore
like this:
import { useMyStore } from './myStore ';
jest.mock('./myStore '); // mock the dependancy store
describe('tests', () => {
const myStoreMock = {
anyStoreAction: jest.fn(),
};
const useMyStoreMock = jest.mocked(useMyStore);
beforeEach(() => {
useMyStoreMock.mockReturnValue(myStoreMock);
setActivePinia(createPinia()); // use the acutal pinia store for store that you are testing
});
});
This is also achivable with Vitest. Just use the equivalent vi
functions.
Upvotes: 2
Reputation: 537
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');
})
Upvotes: 4