我的组件具有以下计算代码:
textButton() { const key = this.$root.feature.name === //... // ... },
现在我拼命地想在我的测试中模拟“root”,但我就是不知道怎么做。有什么建议吗?
c7rzv4ha1#
Vue test utils为您提供了在挂载(或浅挂载)组件时注入模拟的能力。
const $root = 'some test value or jasmine spy' let wrapper = shallow(ComponentToTest, { mocks: { $root } })
这应该很容易测试。希望能帮上忙
z9gpfhce2#
使用vue-test-utils有两种方法可以实现这一点。如上所述,一种方法是使用mocks安装选项。
vue-test-utils
mocks
const wrapper = shallowMount(Foo, { mocks: { $root: { feature: { name: "Some Val" } } } })
但是在您的例子中,您可能希望使用计算的mouting选项,它比mocks中的deep对象更简洁一些。
const wrapper = shallowMount(Foo, { computed: { textButton: () => "Some Value" } })
希望这有帮助!如果你感兴趣的话,我正在编译一系列关于如何测试Vue组件here的简单指南。它正在开发中,但是如果你需要其他与测试Vue组件相关的帮助,请随时提出问题。
hiz5n14c3#
解决方案https://github.com/vuejs/vue-test-utils/issues/481#issuecomment-423716430:你可以直接在虚拟机上设置$root:
wrapper.vm.$root = { loading: true } wrapper.vm.$forceUpdate()
也可以使用parentComponent安装选项传入父元件。在VTU中,paren将是$root:
const Parent = { data() { return { loading: "asdas" } } } const wrapper = shallowMount(TestComponent, { parentComponent: Parent })
cngwdvgl4#
您可以在测试中使用Vue插件将模拟数据注入localVue,以便您的组件可以访问它。
localVue
import {createLocalVue, shallow} from '@vue/test-utils'; const localVue = createLocalVue(); localVue.use((Vue) => { Vue.prototype.feature = { name: 'Fake news!' }; }); let wrapper = shallow(Component, { localVue });
不久前我也遇到了同样的问题,我得出的结论是,访问this.$root可能是一个信号,表明您必须进一步改进与组件通信的方式。例如,考虑使用插件结构来定义全局可用的属性和方法,而不仅仅是在测试中。Mixin也可能有帮助。
this.$root
tyu7yeag5#
对于在Vue 3和Vue Test Utils v2中遇到相同问题的人:我建议使用组件计算变量 Package $root访问。所以,替换这个:
$root
methods: { textButton() { const key = this.$root.feature.name === //... // ... }, }
用这个:
computed: { feature() { return this.$root.feature; } }, methods: { textButton() { const key = this.feature.name === //... // ... }, }
然后在测试实现中,在挂载前模拟这个计算变量:
import { shallowMount } from '@vue/test-utils'; import MyComponent from '<path here>'; MyComponent.computed.feature = jest.fn(() => { name: 'random feature name' }); const wrapper = shallowMount(MyComponent); ...
这样就不需要再模拟$root了。
5条答案
按热度按时间c7rzv4ha1#
Vue test utils为您提供了在挂载(或浅挂载)组件时注入模拟的能力。
这应该很容易测试。希望能帮上忙
z9gpfhce2#
使用
vue-test-utils
有两种方法可以实现这一点。如上所述,一种方法是使用
mocks
安装选项。但是在您的例子中,您可能希望使用计算的mouting选项,它比
mocks
中的deep对象更简洁一些。希望这有帮助!
如果你感兴趣的话,我正在编译一系列关于如何测试Vue组件here的简单指南。它正在开发中,但是如果你需要其他与测试Vue组件相关的帮助,请随时提出问题。
hiz5n14c3#
解决方案https://github.com/vuejs/vue-test-utils/issues/481#issuecomment-423716430:
你可以直接在虚拟机上设置$root:
也可以使用parentComponent安装选项传入父元件。在VTU中,paren将是$root:
cngwdvgl4#
您可以在测试中使用Vue插件将模拟数据注入
localVue
,以便您的组件可以访问它。不久前我也遇到了同样的问题,我得出的结论是,访问
this.$root
可能是一个信号,表明您必须进一步改进与组件通信的方式。例如,考虑使用插件结构来定义全局可用的属性和方法,而不仅仅是在测试中。Mixin也可能有帮助。tyu7yeag5#
对于在Vue 3和Vue Test Utils v2中遇到相同问题的人:
我建议使用组件计算变量 Package
$root
访问。所以,替换这个:用这个:
然后在测试实现中,在挂载前模拟这个计算变量:
这样就不需要再模拟
$root
了。