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.
<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.
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.
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.