vue項目加入单元测试模块,使用jest

本文介绍了如何配置和使用Jest及VueTestUtils来测试Vue的单文件组件(SFC)。步骤包括安装相关依赖、配置项目文件如package.json、jsconfig.js、babel.config.js和jest.config.js,以及解决测试过程中可能出现的环境错误和组件识别问题。此外,还展示了如何编写测试用例,并给出了测试通过的示例。最后,提供了官方教程链接以便进一步学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用Jest测试单文件组件

1、安装 Jest 和 Vue Test Utils

npm install --save-dev jest @vue/test-utils

2、安装和配置 vue-jest 预处理器

npm install --save-dev vue-jest

3、配置相关文件

(1)package.json
// package.json
{
  "scripts": {
    "test": "jest"
  }
}
(2)jsconfig.js
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "exclude": ["node_modules", "dist"]
}

(3)babel.config.js
module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset',
    '@babel/preset-env',
    {
      targets: {
        node: 'current'
      }
    }
  ],
  plugins: ['transform-es2015-modules-commonjs']
}

(4)jest.config.js
module.exports = {
  'verbose': true,
  'moduleFileExtensions': [
    'js',
    'json',
    'vue'
  ],
  'transform': {
    '.*\\.(vue)$': 'vue-jest',
    '^.+\\.js$': '<rootDir>/node_modules/babel-jest'
  },
  'moduleNameMapper': {
    '^@/(.*)$': '<rootDir>/src/$1'
  }
}

4、解决babel解析es6出错问题,配置安装 @babel/preset-env

npm install --save-dev @babel/preset-env

检查babel.config.js配置是否与上面相同。

如果配置没错但系统仍报错,检查package.json,将babel-core模块的版本设置为"^7.0.0-0",重新npm install

5、开始测试

(1)新建HelloWorld.vue
<template>
    <div>
        <span class="count">{{ count }}</span>
        <button @click="increment">Increment</button>
        <button id="subtract" @click="subtract">subtract</button>
    </div>
</template>
<script>
export default {
	data () {
    return {
      count: 1
    }
  },

  methods: {
    increment () {
      this.count++
    },
    subtract () {
      this.count--
    }
  }
}
</script>
(2)新建test.js
/**
 * @jest-environment jsdom
 */
import { mount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld', () => {
  // Now mount the component and you have the wrapper
  const wrapper = mount(HelloWorld)

  it('renders the correct markup', () => {
    expect(wrapper.html()).toContain('<span class="count">1</span>')
  })

  //it's also easy to check for the existence of elements
  it('has a button', () => {
    expect(wrapper.contains('button')).toBe(true)
  })

  it('button should increment the count', () => {
    expect(wrapper.vm.count).toBe(1)
    const button = wrapper.find('button')
    button.trigger('click')
    expect(wrapper.vm.count).toBe(2)
  })
  it('button should subtract the count', () => {
    expect(wrapper.vm.count).toBe(2)
    const button = wrapper.find('#subtract')
    button.trigger('click')
    expect(wrapper.vm.count).toBe(1)
  })
})

(3)运行测试文件
a.直接点击下图红框处运行单文件

在这里插入图片描述

b.使用npm run test执行所有测试文件
(4)测试结果(通过)

在这里插入图片描述

6、报错解决

(1)环境错误
a.错误信息

Test suite failed to run

[vue-test-utils]: window is undefined, vue-test-utils needs to be run in a browser environment.
You can run the tests in node using jsdom
See https://vue-test-utils.vuejs.org/guides/#browser-environment for more details.

b.解决方案

在测试文件最上方添加代码

/**
 * @jest-environment jsdom
 */

在这里插入图片描述

(2)无法识别element组件
a.错误信息

Unknown custom element: - did you register the component correctly? For recursive components……

b.解决方法
import ElementUI from 'element-ui'
import VueRouter from 'vue-router'

// 创建临时Vue实例,挂载组件中使用的插件
const localVue = createLocalVue()
localVue.use(ElementUI)
localVue.use(VueRouter)
const router = new VueRouter()
………………
const wrapper = mount(statisticalOverview, {
    localVue,
    router
  })
………………

7、官方教程

https://vue-test-utils.vuejs.org/zh/api/wrapper/#contains

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JYeontu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值