【Vue 开发实战】实战篇 # 46:如何做好组件的单元测试

简介: 【Vue 开发实战】实战篇 # 46:如何做好组件的单元测试

说明

【Vue 开发实战】学习笔记。



配置 jest.config.js 文件

https://v1.test-utils.vuejs.org/zh/installation/#%E7%94%A8-jest-%E6%B5%8B%E8%AF%95%E5%8D%95%E6%96%87%E4%BB%B6%E7%BB%84%E4%BB%B6


57eab22fbb3941819c7ccfed6a9676f9.png


module.exports = {
    //   preset: "@vue/cli-plugin-unit-jest",
    moduleFileExtensions: [
        "js",
        "jsx",
        "json",
        // tell Jest to handle *.vue files
        "vue",
    ],
    transform: {
        // process *.vue files with vue-jest
        "^.+\\.vue$": require.resolve("vue-jest"),
        ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": require.resolve(
            "jest-transform-stub"
        ),
        "^.+\\.jsx?$": require.resolve("babel-jest"),
    },
    transformIgnorePatterns: ["/node_modules/"],
    // support the same @ -> src alias mapping in source code
    moduleNameMapper: {
        "^@/(.*)$": "<rootDir>/src/$1",
    },
    // serializer for snapshots
    snapshotSerializers: ["jest-serializer-vue"],
    testMatch: [
        "**/*.spec.[jt]s?(x)",
        "**/__tests__/*.[jt]s?(x)"
    ],
    // https://github.com/facebook/jest/issues/6766
    testURL: "http://localhost/",
    // 添加测试报告
    // 是否开启测试报告覆盖率
    collectCoverage: process.env.COVERAGE === "true",
    // 哪些文件作为测试报告的基本数据
    collectCoverageFrom: ["**/*.{js,vue}", "!**/node_modules/**"]
};


修改 .eslintrc.js 的配置

module.exports = {
    root: true,
    env: {
        node: true,
        jest: true,
    },
    extends: ["plugin:vue/essential", "eslint:recommended", "@vue/prettier"],
    parserOptions: {
        parser: "babel-eslint",
    },
    rules: {
        "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
        "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
    },
};



测试 auth.js 文件

启动命令监听

npm run test:unit -- --watch


我们添加一个vscode的插件 Jest Snippets,可以快添加代码

1e80faeb71d04944a03933f83db9acd5.png


修改一下 auth.js 文件

const currentAuth = ["admin"];
export { currentAuth };
export function getCurrentAuthority() {
    return currentAuth;
}
export function check(authority) {
    const current = getCurrentAuthority();
    return current.some(item => authority.includes(item));
}
export function isLogin() {
    const current = getCurrentAuthority();
    return current && current[0] !== "guest";
}



auth.js 文件的同级目录 新建一个 auth.spec.js 的文件进行测试

import { check, currentAuth } from "./auth";
describe('auth test', () => {
    // 权限为空 currentAuth:[]
    it('empty auth', () => {
        // 清空currentAuth
        currentAuth.splice(0, currentAuth.length);
        expect(check(['user'])).toEqual(false);
        expect(check(['admin'])).toEqual(false);
    });
    // 权限为user currentAuth:['user']
    it('user auth', () => {
        currentAuth.splice(0, currentAuth.length);
        currentAuth.push('user');
        expect(check(['user'])).toEqual(true);
        expect(check(['admin'])).toEqual(false);
    });
    // 权限为admin currentAuth:['user', 'admin']
    it('empty admin', () => {
        currentAuth.push('admin');
        expect(check(['user'])).toEqual(true);
        expect(check(['admin'])).toEqual(true);
        expect(check(['user', 'admin'])).toEqual(true);
    });
});


另外删掉了这个例子文件 example.spec.js

33f9fd5875dd4cf7b22da1213ee6ede2.png



测试结果

测试结果如下:

1aecda9035ba426482946457351caeb6.png

目录
相关文章
|
12天前
|
消息中间件 Java 数据库
【消息队列开发】 实现 VirtualHostTests 类——测试虚拟主机操作
【消息队列开发】 实现 VirtualHostTests 类——测试虚拟主机操作
|
12天前
|
消息中间件 存储 测试技术
【消息队列开发】 实现MemoryDataCenterTests类——测试管理内存数据
【消息队列开发】 实现MemoryDataCenterTests类——测试管理内存数据
|
3天前
|
前端开发 Java 测试技术
【SpringBoot】单元测试实战演示及心得分享
【SpringBoot】单元测试实战演示及心得分享
13 0
|
3天前
|
JavaScript API
【vue实战项目】通用管理系统:信息列表,信息的编辑和删除
【vue实战项目】通用管理系统:信息列表,信息的编辑和删除
20 2
|
3天前
|
JavaScript 前端开发 API
【vue实战项目】通用管理系统:学生列表
【vue实战项目】通用管理系统:学生列表
16 2
|
3天前
|
缓存 JavaScript
【vue实战项目】通用管理系统:首页
【vue实战项目】通用管理系统:首页
10 2
|
3天前
|
设计模式 Java 测试技术
Java8实战-重构、测试和调试(二)
Java8实战-重构、测试和调试(二)
7 2
|
3天前
|
设计模式 算法 Java
Java8实战-重构、测试和调试(一)
Java8实战-重构、测试和调试(一)
9 0
|
9天前
|
缓存 JavaScript 前端开发
Nuxt.js实战:Vue.js的服务器端渲染框架
Nuxt.js提供了开发、构建和部署的完整工作流。使用nuxt命令启动开发服务器,nuxt build进行生产构建,nuxt start启动生产服务器
16 0
|
12天前
|
测试技术 程序员 开发者
软件测试项目式学习一(认识软件生命周期与开发模型及软件质量)
软件测试项目式学习一(认识软件生命周期与开发模型及软件质量)
7 0