参考文档:
https://v1.test-utils.vuejs.org/zh/
https://www.jestjs.cn/jest中文文档
第一步安装
@vue/test-utils要指定1.0的版本,否则是vue3的

npm install -D jest vue-jest babel-core babel-jest @vue/vue2-jest jsdom @babel/preset-env jsdom-global @vue/test-utils@1.0.3

如果提示babel-core版本低,则升级为7.0以上,安装如下命令:

npm install --save-dev babel-core@^7.0.0-bridge.0

如果vue-template-compiler报错,请升级为2.7版本。

npm uninstall vue-template-compiler
npm i vue-template-compiler@2.7.11

第二步 配置
1 根目录新建jest.config.js

const path = require('path');
module.exports = {
  rootDir: path.resolve(__dirname, './'), // 根据自己项目来
  moduleFileExtensions: [
    "js",
    "json",
    "vue"
  ],
  transformIgnorePatterns: ["/node_modules/"],
  testEnvironment: "node",
  collectCoverage: true,
  collectCoverageFrom: [
    "**/src/components/**/*.{js,vue}"
  ],
  testRegex: '(/tests/unit/.*\\.(test|spec))\\.[tj]sx?$',//测试文件的地址配置
  transform: {
    "^.+\\.js$": "<rootDir>/node_modules/babel-jest",//告诉 Jest 用 babel-jest 处理 JavaScript 测试文件
    ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"//告诉 Jest 用 vue-jest 处理 .vue 文件
  },
  moduleNameMapper:{
    "^@/(.*)$": "<rootDir>/$1"
  },     
  setupFiles: ['<rootDir>jest.setup.js'], //启动jest需要的文件
  testEnvironmentOptions: {
    url: "http://localhost"
  }
};

2 根目录新建jest.setup.js

require('jsdom-global')();

3 根目录新建tests/utils/xxx.test.js
然后就可以在xxx.test.js写测试案例了。
例如:

// jest是执行测试用例的工具,运行npm run test,就会找到所有的.test.js文件并行执行。
// 想要测试某个组件,直接引入该组件,然后编写测试用例代码
// 想要测试某个js方法也可以。

import { createLocalVue, shallowMount } from '@vue/test-utils';
import ElementUI from 'element-ui';
const localVue = createLocalVue();
localVue.use(ElementUI);
import DetailField from '@/src/views/UopBusiFront/JreEngine/FieldManage/DetailField';
describe('DetailField', () => {
  it('有el-dialog', () => {
    const wrapper = shallowMount(DetailField, {localVue});
    const elForm = wrapper.find('el-dialog');
    expect(elForm.exists()).toBe(true);
  })
})

4 package.json配置

"test": "jest"

5 babel.config.js

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

配置完成后,运行npm run test即可测试。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐