網站搜尋

javascript - 使用 Vue.js 在 test 中查找資料屬性


嘗試弄清楚如何使用 shallowMount 在 Vue 模板中找到一個 data 屬性並檢查該屬性是否存在:

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
});

但我不確定該如何著手,顯然這樣做是不對的。我是一個酶和 React 的人,正在努力弄清楚如何用 Vue 做同樣類型的測試。

注意:我使用 shallowMount 僅僅是為了 TDD。我對 mount() 不感興趣,也不打算在這篇文章中辯論這個問題。我只是想請教關於 shallowMount 的幫助,以及如何找到一個資料屬性以便我的測試進行斷言。

答案#1

假設資料集就在封裝器本身中,使用封裝器屬性()。

即

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"]
  })
})

CodeSandbox 示範