简体   繁体   中英

Find a data-attribute in test with Vue.js

Trying to figure out with shallowMount how I can find a data attribute and check if that attribute is there in the Vue template:

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 (using Vue Test Utils and mocha):

it('shows an apple', () => {
  let fakeStore = new Vuex.Store({ state: {} });
  const apple = shallowMount(myVue, {fakeStore}),

  expect(apple).to.have.length(1);
});

OR maybe this way???

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

but I'm not sure how to go about it, obviously this is not right. I'm an enzyme and React guy trying to figure out how to do the same kinds of tests with Vue basically.

Note : I use shallowMount solely for TDD I am not interested in mount() and I'm not about to debate that right now for this post. I'm just asking help for shallowMount here and how to find aa data-attribute for my tests to assert on.

Use wrapper attributes() assuming the dataset is in the wrapper itself.

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

To search for a child that has a dataset use 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 Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM