yeti blue
yeti blue

Reputation: 271

Vue Jest Pass Data to Component

new to testing and was wondering if there was another way to inject data back to the component other than what's on the docs

The Docs

const Component = {
  template: `
    <div>
      <span id="foo">{{ foo }}</span>
      <span id="bar">{{ bar }}</span>
    </div>
  `,

  data() {
    return {
      foo: 'foo',
      bar: 'bar'
    }
  }
}

const wrapper = mount(Component, {
  data() {
    return {
      bar: 'my-override'
    }
  }
})

wrapper.find('#foo').text() // 'foo'
wrapper.find('#bar').text() // 'my-override'

It seems like the relevant parts of the component are copied (mocked?) into the test itself and the test + data are self-containing. Is there a way to send the data back into the component and test what's there?

Ideally I want to be able to tweak the value of a variable from the test, and then have that pass to the component to display the correct card.

Something like:

<template>
  <div id="wrapper">
    <div v-if="cardOne" id="card1">Text 1</div>

    <div v-if="cardTwo" id="card2">Text 2</div>
  </div>
</template>
<script>
export default {
  methods: {
    //loop to go through numberArray
    // if x = 1, this.cardOne = true and card1 is shown
    // if x=2, this.cardTwo = true and card2 is shown etc

    //Can I manually set x = 1 from the test, and then see if cardOne renders on the component?
  },
  data() {
    return {
      numberArray: [1, 2],
      cardOne: false,
      cardTwo: false
    };
  }
};
</script>

Upvotes: 2

Views: 1059

Answers (1)

Eduardo
Eduardo

Reputation: 1321

If your component gets data via props you can use props (Vue 3) or propsData (Vue 2) property of options object to pass data to it when you call shallowMount/mount.

If your component has some default values after instantiation and you want to change them your way is correct. You pass data via data method and if you want to change these values later in the test you should use setData method of your wrapper instance as it's shown in docs. API of this method is the same for both Vue 2 and Vue 3 apps.

Upvotes: 2

Related Questions