vue2项目集成Jest单元测试

2,748 阅读1分钟

包的安装

npm install -D jest babel-core babel-jest @vue/vue2-jest jsdom @babel/preset-env

该安装命令将会安装最新版本 jest 以及 对应版本的 @vue/vue2-jest

相关对应表

Vue versionJest VersionPackage
Vue 2Jest 26 and belowvue-jest@4
Vue 3Jest 26 and belowvue-jest@5
Vue 2Jest 27@vue/vue2-jest
Vue 3Jest 27@vue/vue3-jest

剩下的就是 Babel 相关的包。

jsdom 在挂载 .vue 组件时会用到。

@babel/preset-env 用来解决代码中的 import/export 无法被识别报错的问题。

创建配置文件

babel 配置

在项目根目录创建或者编辑 .babelrc 文件,在文件中新增以下配置

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "current"
                }
            }
        ]
    ]
}

jest 配置

在项目根目录新增或编辑 jest.config.js 文件,在文件中新增以下配置

module.exports = {
    testEnvironment: "jsdom",
    "transform": {
        "^.+\.js$": "babel-jest",
        "^.+\.vue$": "@vue/vue2-jest"
    },
    "moduleFileExtensions": [
        "js",
        "vue"
    ],
    transformIgnorePatterns: ["<rootDir>/node_modules/"]
};

新增单元测试命令

修改 package.json, 在 scripts 中加入 "test": "jest"

新增单元测试文件

在组件目录新增文件 Footer.spec.js

import { shallowMount } from "@vue/test-utils";
import Footer from "~/components/Footer";

test("Footer component", () => {
    const wrapper = shallowMount(Footer);
    expect(wrapper.text()).toContain("公司首页")
});

搞定

参考

jest在node中使用:jest Cannot use import statement outside a module

vue-jest github

官方文档

vue.js应用测试