Har*_*old 7 unit-testing vuejs2 vue-test-utils
vue-test-utils提供了一个setComputed方法,允许您设置计算属性的状态.
import { mount } from '@vue/test-utils'
const wrapper = mount(Home)
wrapper.setComputed({loaded: true})
Run Code Online (Sandbox Code Playgroud)
vue-test-utils版本1.1.0.beta正在为读取的setComputed方法抛出弃用警告 setComputed() has been deprecated and will be removed in version 1.0.0. You can overwrite computed properties by passing a computed object in the mounting options
const wrapper = mount(Home, { computed: {loaded: true} })
Run Code Online (Sandbox Code Playgroud)
和
const wrapper = mount(Home, {context: { computed: {loaded: true} } })
Run Code Online (Sandbox Code Playgroud)
但那些爆炸了.
为vue-test-utils设置计算属性的方法是什么?
itt*_*tus 13
您可以在装入组件时覆盖计算选项:
const wrapper = mount(Home, {
computed: {
loaded() {
return true
}
}
})
Run Code Online (Sandbox Code Playgroud)
但是模拟计算是危险的.您可能会将组件置于生产期间无法进入的状态.
在 Vue 3(及其当前合作伙伴 Vue Test Utils v2 RC 18)中,您仍然可以像 @ittus 提到的那样存根结果:
const wrapper = mount(Home, {
computed: {
loaded() {
return true
}
}
})
Run Code Online (Sandbox Code Playgroud)
然而,有一个问题,至少在使用优秀的 vue-class-component (v8 RC 1) 时是这样。
如果您开始对一个计算属性进行存根,则必须对所有属性进行存根。否则,它们返回时的值将是未定义的。
所以在这种情况下:
export default class Home extends Vue {
public get loaded(): boolean {
return true
}
public get tipsy(): boolean {
return true
}
}
Run Code Online (Sandbox Code Playgroud)
如果按照上面的方式安装它,那么结果是:
wrapper.vm.loaded === true // true
wrapper.vm.tipsy === undefined // true
Run Code Online (Sandbox Code Playgroud)
但是,如果您在挂载时对它们进行存根:
const wrapper = mount(Home, {
computed: {
loaded() {
return true
},
tipsy() {
return false
}
}
})
Run Code Online (Sandbox Code Playgroud)
那么结果是这样的:
wrapper.vm.loaded === true // true
wrapper.vm.tipsy === false // true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4689 次 |
| 最近记录: |