Testing Props in Vue components using Jest
In this tutorial, we are going to learn about how to test props in vue components using jest and vue-test-utils.
Props in vue components help us to pass the data from parent components to child components.
The example component we are testing.
<template>
<h1>{{title}}</h1></template>
<script>
export default {
props:['title']};
</script>
In the above component, we have declared a prop
called title
.
When we unit test a component we need to provide a correct prop to the component at the time of mounting. so that we can test does the component is receiving correct props are not.
In vue-test-utils shallowMount
method takes an options
object as a second argument by using this object we can pass props to the component.
Let’s write a test for the Post.vue
component.
import Post from '../src/components/Post.vue'
import { shallowMount } from '@vue/test-utils';
describe('Testing Component props', () => {
const wrapper = shallowMount(Post, {
propsData: {
title: "First post" //passing prop to component }
});
it('checks the prop title ', () => {
expect(wrapper.props().title).toBe('First post'); })
})
In the above code, we first passed a prop to the component inside shallowMount
method and it returns a wrapper
object which contains a props()
method.
The props()
method returns an object
containing props of the component currently have, like in the above code we are asserting the prop title
has a value First post
.