在已有vue cli项目中添加单元测试配置

发布于:2025-02-11 ⋅ 阅读:(29) ⋅ 点赞:(0)

使用的是vue cli ^4.0.0的脚手架,项目采用的vue2进行编写,项目本身是没有使用单元测试的。应该挺多项目还是使用的vue2的项目进行开发的,自己在开发中过程中,还是发生了挺多需要记录原来功能的情况,这个时候去翻文档明显是不怎么可取的,且项目中文档不一定写的很好。

安装的依赖

pnpm i -D @vue/cli-plugin-unit-jest@4 @vue/test-utils@1 jest@26 @vue/vue2-jest@26 babel-jest@26

增加执行测试的脚本

文档路径:package.json

{
    "scripts": {
        // ...
        "test:unit": "jest",
    }
}

增加jest配置

文档路径:jest.config.js

module.exports = {
    preset: '@vue/cli-plugin-unit-jest',
    collectCoverage: false,
    collectCoverageFrom: [
        'src/**/*.{js,vue}',
        '!src/main.js',
        '!src/router/index.js',
        '!src/store/**/*.js',
        '!**/node_modules/**',
    ],
};

修改babel的配置

文档路径:.eslintrc.js

module.exports = {
    // ...
    env: {
        // ...
        jest: true,
    },
}

测试的组件

文件路径:tests\unit\components\formModule.spec.js,默认的测试文件的路径匹配到**/tests/unit/**/*/之下的文件中,所以按这个路径放文件就可以测试到

import { mount } from '@vue/test-utils';
import formModule from '@/components/form/formModule.vue';

describe('测试组件formModule.vue', () => {
    it('测试表单模块标题', () => {
        const title = '基本信息';
        const wrapper = mount(formModule, {
            propsData: {
                title,
            },
        });
        expect(wrapper.text()).toMatch(title);
    });
});

执行测试

npx pnpm test:unit

如果使用collectCoverage: true的配置的话, 可以生成代码的覆盖率

其他安装依赖的问题

问题1:TypeError: (0 , _vueJest.describe) is not a function

解决:在eslint中的env中添加jest为true

问题2:TypeError: Cannot destructure property ‘ensureValidVNode’ of ‘Vue.ssrUtils’ as it is undefined

解决:安装npx pnpm i -D @vue/test-utils@1


网站公告

今日签到

点亮在社区的每一天
去签到