说明
【Vue 开发实战】学习笔记。
配置 jest.config.js 文件
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
,可以快添加代码
修改一下 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
测试结果
测试结果如下: