Vue 3 Pina 尝试测试依赖于另一个商店的 pina 商店

问题描述 投票:0回答:2

我基本上有一个商店依赖于另一个商店,但我没有找到一种方法来仅模拟依赖商店。 示例伪代码 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');
})

javascript unit-testing jestjs vuejs3
2个回答
4
投票

对你有帮助。

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

默认情况下,任何 getter 都会像常规用法一样进行计算 但是您可以 通过将 getter 设置为您想要的任何值来手动强制指定值

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');
})

0
投票

我通过模拟导入的

useStore
解决了这个问题:

import { useXyStore } from './xyStore ';
jest.mock('./xyStore '); // mock the dependancy store

describe('tests', () => {
    const xyStoreMock = {
         anyStoreAction: jest.fn(),
    };
    const useXyStoreMock = jest.mocked(useXyStore);
    
    beforeEach(() => {
         useXyStoreMock.mockReturnValue(xyStoreMock);
         setActivePinia(createPinia()); // use the acutal pinia store for store that you are testing
    });
});

这也可以通过 Vitest 实现。只需使用等效的

vi
函数即可。

© www.soinside.com 2019 - 2024. All rights reserved.