javascript - Vue 和 Jest 单元测试组件

标签 javascript unit-testing vue.js vuejs2 jestjs

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

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

目前我有这样的事情,但我不知道如何继续

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官方文档非常清楚和有用。要了解如何模拟函数、 stub 和其他测试内容,请参阅 Jest 文档。

对于您的示例 - 使用 propsData 而不是 props(检查上面的文档)并且您应该以一些断言(检查期望)结束每个测试用例:

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

关于javascript - Vue 和 Jest 单元测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51520835/

相关文章:

javascript - jQuery限制 "Dropdown Check List"选择

angularjs - Jasmine 单元测试 $timeout (expect($timeout).toHaveBeenCalledWith(n);)

unit-testing - MSTest 内存不足异常

http - 如何在 vue-cli 中设置 HTTP header ?

javascript - 如何在vue js中设置一天的默认日期

javascript - 未捕获的类型错误 : Cannot read property 'apply' of undefined phaser

javascript - 等间距且对齐的水平列表菜单

vue.js - 在另一个仓库中导入 vue-cli 应用程序时出错

javascript - 使用请求 promise 移动到新页面的最佳方法?

java - 对象没有被 mock 。抛出空指针异常