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.

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.