我有一个 Vue 组件。 我的组件有一个计算属性,它引用 vuex 存储的 getter。
当此 getter 更新时,我使用手表执行一些操作。
我想使用 jest 和 vue-test-utils 测试手表。
我该怎么办?
要测试 Vue 组件中的手表(当 Vuex 存储中的事件 getter 更新时触发),您可以使用 Jest 和 vue-test-utils 按照以下步骤操作:
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
const store = createStore({
modules: {
global: {
getters: {
event: jest.fn(), // Mock the event getter
},
},
},
});
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