基于jest的vue项目单元测试

1,128 阅读1分钟

一、测试环境搭建

gitHub下载 github.com/linhnogjie/…
相关依赖
  • jest
  • vue-jest
  • babel-jest
  • @vue/test-utils
安装依赖
    npm/cnpm install jest vue-jest babel-jest @vue/test-utils -D
项目架构

编写jest配置文件
    //jest.conf.js
    const path = require('path');
    module.exports = {
      verbose: true,
      rootDir: path.resolve(__dirname, '../../'), // 同 webpack.context
      moduleFileExtensions: [ // 同 webpack.resolve.extensions
        'js',
        'json',
        'vue',
      ],
      moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1', // 同 webpack.resolve.alias
      },
      transform: { // 同 webpack.module.rules
        '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
        '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
      },
      setupFiles: ['<rootDir>/test/unit/setup'], // 同 webpack.entry
      coverageDirectory: '<rootDir>/test/unit/coverage', // 同 webpack.output
      collectCoverageFrom: [ // 同 webpack 的 rule.include
        '**/*.{js,vue}',
        '!src/main.js',
        '!src/router/index.js',
        '!**/node_modules/**',
      ],
    };

编写jest启动文件
    //setup.js
    import Vue from 'vue';
    import { config } from '@vue/test-utils';
    
    Vue.config.productionTip = false;
    
    // 可在此处设置全局对象
    config.provide.GLOBAL = {
      logined: false,
    };

在webpack.js中添加
    "scripts": {
      "unit": "jest --config test/unit/jest.conf.js --coverage",
    },

二、编写测试案例

有一个组件
<template>
  <div>
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      msg: 'Hello Jest',
    };
  },
};
</script>
对上面组件进行测试用例编写
import { shallowMount } from '@vue/test-utils';
import HelloWorld from './hello-world';

describe('<hello-world/>', () => {
  it('should render correct contents', () => {
    const wrapper = shallowMount(HelloWorld);
    expect(wrapper.find('.hello h1').text())
      .toEqual('Welcome to Your Vue.js App');
  });
});
运行测试
npm run unit

三、参考

对vue-router进行测试 www.jb51.net/article/150…
测试用例实战参考 www.jianshu.com/p/38a37d5fc…
jest断言归纳 www.jianshu.com/p/c1b5676c1…
Vue Test Utils 参考API vue-test-utils.vuejs.org/zh/api/