简体   繁体   中英

Vue and Jest unit testing components

I'm pretty new in Vue js , and I'm starting with unit testing with Jest . I don't have any idea where and how to start. I have this piece of Vue code that i would like to test using Jest. Any tips or idea I'll be so thankful. I read that I should use shallowMount from Vue test-utils to avoid troubles during the component testing

<template >
  <div class="wrapper">
    <div class="user">
      <span>{{ user.substr(0, 4) }}</span>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    user: {
      type: String,
      required: true
    }
  }
}
</script>

At the moment I have something like this, but I don't know how to conitnue

import { shallowMount } from '@vue/test-utils'
import User from '../User.vue'


describe('User', () => {
  it('Should substract four letters', () => {
    const wrapper = shallowMount(User, {
      props: {
        ''
      }
    })
  })
})

You can read vue-test-utils official documentation it's very clear and helpful. Also to learn how to mock functions, stubs and other test things see Jest docs.

And with your example - use propsData instead of props (check docs above) and you should end each your test case with some assertion (checking expectations):

describe('User', () => {
   it('Should substract four letters', () => {
      const wrapper = shallowMount(User, {
      propsData: {
        user: 'User00000000'
      }
    })
   // check that span element has correct substring
   expect(wrapper.find(".user span").text()).toBe('User');
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM