使用 Vue.js 在测试中查找数据属性

Pos*_*Guy 5 javascript vue.js

尝试使用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>
Run Code Online (Sandbox Code Playgroud)

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);
});
Run Code Online (Sandbox Code Playgroud)

或者也许这样???

myVue.vue

<template>
    <div>
        <div apple></div>
    </div>
</template>
Run Code Online (Sandbox Code Playgroud)

规范.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
});
Run Code Online (Sandbox Code Playgroud)

但我不知道该怎么做,显然这是不对的。我是一名酶和 React 专家,试图弄清楚如何基本上使用 Vue 进行相同类型的测试。

注意:我仅将shallowMount 用于TDD,我对mount() 不感兴趣,并且我现在不打算在这篇文章中争论这一点。我只是在这里寻求关于shallowMount 的帮助以及如何为我的测试找到要断言的数据属性。

Ric*_*cky 6

使用包装器attribute()假设数据集位于包装器本身中。

IE。

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')
  })
})
Run Code Online (Sandbox Code Playgroud)

要搜索具有数据集的子项,请使用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"]
  })
})
Run Code Online (Sandbox Code Playgroud)

CodeSandbox 演示

  • @PositiveGuy 我提供了一个 CodeSandbox 演示,您也可以使用它来解决有关“vue-test-utils”的未来问题/问题,可能会派上用场“:)”。 (2认同)