javascript - 使用 Vue.js 在 test 中查找数据属性
尝试用 shallowMount 找出如何在 Vue 模板中找到一个数据属性并检查该属性是否存在:
myVue.vue
<template>
<div>
<div data-test="apple"></div>
</div>
</template>
<script>
export default {
name: "fruit-main",
extends: registerStore(),
components: {
},
props: {
},
data() {
},
mounted() {
},
computed: {
},
methods: {
},
watch: {
}
}
</script>
spec.js(使用 Vue Test Utils 和 mocha):
it('shows an apple', () => {
let fakeStore = new Vuex.Store({ state: {} });
const apple = shallowMount(myVue, {fakeStore}),
expect(apple).to.have.length(1);
});
或者这样???
myVue.vue
<template>
<div>
<div apple></div>
</div>
</template>
spec.js
it('shows an apple', () => {
const vue = shallowMount(myVue),
apple = vue.element.getAttribute('apple')
expect(apple).to.exist
// or expect(apple).to.have.length(1); - which is how you'd do it with enzyme but I'm not sure yet what getAttribute returns yet
});
但是我不确定该如何进行,显然这样不对。我是一个酶(enzyme)和 React 人,正在试图弄明白如何用 Vue 做同样类型的测试。
注意:我使用 shallowMount 完全是为了 TDD,我对 mount() 不感兴趣,而且我现在也不会为这篇文章去辩论这个。我这里只是想寻求关于 shallowMount 的帮助,以及如何找到我的测试中可以断言的数据属性。
答案#1
使用 wrapper attributes(),假设数据集本身就在 wrapper 中。
即
import FruitMain from '@components/FruitMain.vue'
import { shallowMount } from '@vue/test-utils'
describe('@components/FruitMain.vue', () => {
it('shows an apple', () => {
// We are assuming the FruitMain component receives a 'fruit' prop.
const wrapper = shallowMount(FruitMain, { propsData: { fruit: 'apple' } })
// Has the correct starting data fruit
expect(wrapper.attributes()['data-fruit']).toBe('apple')
// Has the correct fruit value when props change
// wrapper.setProps({ fruit: 'banana' })
// expect(wrapper.attributes()['data-fruit']).toBe('banana')
})
})
要搜索包含数据集的子项,请使用 contains()。
import FruitMain from '@components/FruitMain.vue'
import { shallowMount } from '@vue/test-utils'
describe('@components/FruitMain.vue', () => {
it('shows an apple', () => {
// We are assuming the FruitMain component receives a 'fruit' prop.
const wrapper = shallowMount(FruitMain, { propsData: { fruit: 'apple' } })
// Has a data fruit
expect(wrapper.contains('[data-fruit]')).toBe(true) // or [data-fruit="apple"]
})
})
