如何使用 jest 和 vue-test-utils 在链接到存储 getter 的计算属性上测试手表?

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

我有一个 Vue 组件。 我的组件有一个计算属性,它引用 vuex 存储的 getter。

当此 getter 更新时,我使用手表执行一些操作。

我想使用 jest 和 vue-test-utils 测试手表。

我该怎么办?

vue.js jestjs vuex watch vue-test-utils
1个回答
0
投票

要测试 Vue 组件中的手表(当 Vuex 存储中的事件 getter 更新时触发),您可以使用 Jest 和 vue-test-utils 按照以下步骤操作:

  1. 安装必要的依赖项
  2. 为您的 Vue 组件创建一个测试文件(例如 MyComponent.spec.js)
  3. 导入所需的依赖项:
    import { mount } from '@vue/test-utils';
    import MyComponent from '@/components/MyComponent.vue'; // Replace with your component's path
    import { createStore } from 'vuex'; // Import Vuex's createStore function
  1. 使用 getter 创建一个模拟 Vuex 存储:
    const store = createStore({
      modules: {
        global: {
          getters: {
            event: jest.fn(), // Mock the event getter
          },
        },
      },
    });
  1. 编写测试代码并使用 mount 为您的组件创建包装器:
    describe('MyComponent', () => {
      it('should perform action when the event getter is updated', async () => {
        const wrapper = mount(MyComponent, {
          global: {
            plugins: [store], // Pass the Vuex store to the component
          },
        });
       
        // Simulate updating the event getter in the store
        store.getters.event.mockReturnValueOnce('new value');
       
        // Wait for Vue to update the component
        await wrapper.vm.$nextTick();
       
        // Assert the action performed or check the component state
        expect(wrapper.vm.someData).toBe('expected value');
      });
    });

确保使用实际组件、存储以及与您的场景相关的任何特定详细信息更新代码。 使用 Jest 运行测试:

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