2
votes

I want to test a Vue single file component which receives a prop as input. When I mock the prop, which is an object, I get an error that the object is undefined, The error comes from the HTML where the values of the object are used. If I make the prop to be a string for example (and I remove answer.value and :class="{'active': answer.selected}" from HTML), everything works fine.

Component:

<template>
  <div class="answer-container" @click="setActiveAnswer()" :class="{'active': answer.selected}">
    <div class="answer">
      <p>{{answer.value}}</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Answer',
  props: {
    answer: Object,
  },
  methods: {
    setActiveAnswer() {
      this.$emit('selectedAnswer', this.answer);
    }
  }
}
</script>

Test file:

import { mount } from '@vue/test-utils'
import Answer from './../../src/components/Answer'

describe('Answer', () => {

  it('should receive "answer" as prop', () => {
    const answer = {
      value: 'testAnswer',
      selected: true
    };
    const wrapper = mount(Answer, {
      propsData: {
        answer: answer
      }
    });
    expect(wrapper.props().answer.value).toBe('testAnswer');
  })
})

The error I get is:

TypeError: Cannot read property 'selected' of undefined

Please advise what am I doing wrong. Thanks!

1
I just copied your code and ran it on my machine, there's nothing wrong. The test has passed.You Nguyen
Thanks for checking. I fixed it by adding a v-if on the div which uses the prop.decebal

1 Answers

0
votes

I managed to fix this by adding a v-if="answer" on <div class="answer-container" ..., which is quite strange (as this is not async data) since the code works fine when checking the application in the browser - the problem only appeared while unit testing the component. I suppose there is also a fix in a Jest/Unit testing way, something like declaring the prop after the component finished rendering/mounting...