Vue和Jest单元测试组件 [英] Vue and Jest unit testing components

查看:612
本文介绍了Vue和Jest单元测试组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Vue js 中是个新手,我开始使用 Jest 进行单元测试.我不知道从哪里开始以及如何开始.我有一段Vue代码,我想使用Jest进行测试.任何提示或想法,我都会非常感激. 我读到应该使用 Vue test-utils 中的 shallowMount 来避免在组件测试期间出现麻烦

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: {
        ''
      }
    })
  })
})

推荐答案

您可以阅读 vue-test- utils 官方文档,它非常清楚而且很有帮助.另外,要了解如何模拟函数,存根和其他测试内容,请参见Jest文档.

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.

在您的示例中-使用propsData而不是props(请检查上面的文档),然后应在每个测试用例前声明一些断言(检查期望):

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');
  })
})

这篇关于Vue和Jest单元测试组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆