Vue组件单元测试报错:mount.context仅适用于函数式组件
问题解决步骤
1. 移除错误的context配置
你的Toast组件是非函数式组件,mount.context仅适用于函数式组件,所以需要直接通过props选项传递属性,而非嵌套在context中。
2. 修正拼写错误
测试代码里的exitst()是拼写错误,需改为exists()。
3. Mock Vuex Store
组件在mounted钩子中调用了this.$store.commit,单元测试时必须mock这个store实例,避免出现Cannot read property 'commit' of undefined的报错。
4. 调整最后一个测试的断言逻辑
组件本身不会主动销毁自己,它是通过提交store的setNotification mutation,让父组件(App.vue)通过v-if控制销毁。因此最后一个测试应验证经过5.5秒后是否正确调用了对应的mutation,而非断言组件是否存在。
修正后的完整测试代码
import { shallowMount } from "@vue/test-utils"; import Toast from '../../common/Toast.vue'; describe('src/components/common/Toast.vue', () => { // 每个测试前初始化mock store let mockStore; beforeEach(() => { mockStore = { commit: jest.fn() }; }); it('should render with an error class when an error notification is passed to it', () => { const wrapper = shallowMount(Toast, { props: { type: 'error', message: 'This is an error message' }, mocks: { $store: mockStore } }); expect(wrapper.find('.toast--error').exists()).toBeTruthy(); expect(wrapper.find('.toast--success').exists()).toBeFalsy(); }) it('should render with a success class when a success notification is passed to it', () => { const wrapper = shallowMount(Toast, { props: { type: 'success', message: 'This is a success message' }, mocks: { $store: mockStore } }); expect(wrapper.find('.toast--success').exists()).toBeTruthy(); expect(wrapper.find('.toast--error').exists()).toBeFalsy(); }); it('should render the appropriate message from the prop', () => { const wrapper = shallowMount(Toast, { props: { type: 'success', message: 'I am the notification content' }, mocks: { $store: mockStore } }); expect(wrapper.find('.toast-content').text()).toEqual('I am the notification content') }); it('should commit setNotification mutation after 5.5 seconds', () => { jest.useFakeTimers(); const wrapper = shallowMount(Toast, { props: { type: 'success', message: 'I am the notification content' }, mocks: { $store: mockStore } }); // 快进至超时时间点 jest.advanceTimersByTime(5500); // 验证mutation调用是否符合预期 expect(mockStore.commit).toHaveBeenCalledWith('setNotification', {}); jest.useRealTimers(); }); });
额外注意点
App.vue中Toast组件的props传递存在小错误::msg="notification.message"应改为:message="notification.message",因为组件定义的props是message而非msg,虽不是本次测试报错的原因,但会导致实际运行时消息无法正常显示。
内容的提问来源于stack exchange,提问作者Udders
相关产品推荐
相关产品推荐

