by Sai gowtham

Testing Vue.js classes and styles using jest

Testing Vue.js classes and styles using jest

In this tutorial, we are going to learn about how to test the classes and styles in vue by using jest and vue-test-utils.

If you don’t know how to configure jest with vue, you can check out my testing introduction tutorial.

The example component we are testing.

Post.vue
<template>
  <div class="post" style="color:black">    <h1>This is post title</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
  </div>
</template>
<script>
export default {};
</script>

In this component, we have a div element with post class and style attribute.

Let’s write tests for this component.

Testing component classes

Vue-test-utils provides us a classes() method, it returns the array of class names of the root element.

Post.test.js
import { shallowMount } from '@vue/test-utils';
import Post from '../src/components/Post.vue'
describe('Testing classes and style', () => {
    const wrapper = shallowMount(Post);
    it('checks the class to be post', () => {
        expect(wrapper.classes()).toContain('post');    })
})

In the above test, we are checking for the root element has a class name post.

Testing component style

We can directly access the style property inside the wrapper.element object.

Post.test.js
import Post from '../src/components/Post.vue'
import { shallowMount } from '@vue/test-utils';
describe('Testing classes and style', () => {
    const wrapper = shallowMount(Post);
    it('checks the class ', () => {
        expect(wrapper.classes()).toContain('post');
    })

    it('checks the inline style color:black', () => {
        expect(wrapper.element.style.color).toBe('black')    })
})

Note: By default wrapper object contains the root element class names and style, If you want to test the particular element classes in your component you need to use find( ) method.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course