当前位置:编程学习 > > 正文

vue单元测试实例(Vue-Jest 自动化测试基础配置详解)

时间:2021-10-09 00:51:48类别:编程学习

vue单元测试实例

Vue-Jest 自动化测试基础配置详解

目前开发大型应用,测试是一个非常重要的环节,而在 Vue 项目中做单元测试可以用 Jest,Jest 是 facebook 推出的一款测试框架,集成了 Mocha, chai, jsdom, sinon 等功能,而且在 Vue 的脚手架中已经集成了 Jest,所以在 Vue 项目中使用 Jest 做单元测试是不二的选择,从提供的例子上看都很简单地配置并测试成功,然而在实际项目中有很多差异,我在测试自己的某个业务组件就报出很多错误,本文就总结一下自己的踩坑经历,并帮助读者快速解决配置中出现的问题。

安装

可以通过官方提供的 @vue/cli 直接创建 Vue 项目,然后选中 Unit Testing 这个选项

  • ? Check the features needed for your project:
     ◉ Choose Vue version
     ◉ Babel
    ❯◉ TypeScript
     ◯ Progressive Web App (PWA) Support
     ◉ Router
     ◉ Vuex
     ◯ CSS Pre-processors
     ◯ Linter / Formatter
     ◉ Unit Testing
     ◯ E2E Testing
    
    
  • 然后在测试框架中选择 Jest

  • ? Pick a unit testing solution: Jest
    ? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated con
    fig files
    
    
  • Vue + Ts 的项目最终生成的 jest.config.js 配置文件长这样,好像在告诉我们,我都给你们设置好了,直接用吧,然而针对项目,还需要手动去配置兼容,要不然会报出很多错误,无法进行下去。

  • module.exports = {
      preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel'
    }
    
    
  • 配置

    先看看这个预设配置到底写了什么,找到 @vue/cli-plugin-unit-jest/presets/typescript-and-babel 这个包,实际上这个输出的配置如下:

  • module.exports = {
      moduleFileExtensions: [ // 测试的文件类型
        'js',
        'jsx',
        'json',
        // tell Jest to handle *.vue files
        'vue',
        'ts',
        'tsx'
      ],
      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'),
        '^.+\\.tsx?$': require.resolve('ts-jest'),
      },
      transformIgnorePatterns: ['/node_modules/'],  // 转化时忽略 node_modules
      // support the same @ -> src alias mapping in source code
      moduleNameMapper: { // @符号 表示当前项目下的src
        '^@/(.*)$': '<rootDir>/src/$1'
      },
      testEnvironment: 'jest-environment-jsdom-fifteen',
      // serializer for snapshots
      snapshotSerializers: [ // 快照的配置
        'jest-serializer-vue'
      ],
      testMatch: [ // 默认测试文件
        '**/tests/unit/**/*.spec.[jt]s?(x)',
        '**/__tests__/*.[jt]s?(x)'
      ],
      // https://github.com/facebook/jest/issues/6766
      testURL: 'http://localhost/',
      watchPlugins: [
        require.resolve('jest-watch-typeahead/filename'),
        require.resolve('jest-watch-typeahead/testname')
      ],
      globals: {
        'ts-jest': {
          babelConfig: true
        }
      }
    }
    
    
  • 其中比较重要的配置,也是我们比较多用来解决问题的配置:

    常见错误

    SyntaxError : 语法错误,很可能是因为没有进行转化,比如下面的提示:

  •  /Users/zhuangbing.cai/Documents/workspace/projects/wms-ui/node_modules/vue-runtime-helpers/dist/normalize-component.mjs:76
        export default normalizeComponent;
        ^^^^^^
    
        SyntaxError: Unexpected token 'export'
    
  • 由于我们没有对 .mjs 文件进行转换导致了报错,最快的解决方式就是在 transform 补充 .mjs 的转化

  • transform: {
         '^.+\\.mjs$': 'babel-jest'
    }
    
    
  • 只需要在对 .mjs 的文件,提供转化方式即可。

    另一种语法错误,是node_module 内的某些文件需要转化,然而被 transformIgnorePatterns 配置忽略了。

  •     Here's what you can do:
         • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
         • If you need a custom transformation specify a "transform" option in your config.
         • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
    
        You'll find more details and examples of these config options in the docs:
        https://jestjs.io/docs/en/configuration.html
    
        Details:
    
        /Users/zhuangbing.cai/Documents/workspace/projects/wms-ui/node_modules/vue-runtime-helpers/dist/normalize-component.mjs:76
        export default normalizeComponent;
        ^^^^^^
    
        SyntaxError: Unexpected token 'export'
    
    
  • 图中 vue-runtime-helpers 被用到了,然而因为 transformIgnorePatterns  的配置忽略了转化,从而导致语法错误。解决方法就是改变 transformIgnorePatterns  的配置,如下:

  • transformIgnorePatterns: [
        // 转化时忽略 node_modules,但不包括 vue-runtime-helpers
        '/node_modules/(?!(vue-runtime-helpers)/)',
      ],
    
    
  • 将 vue-runtime-helpers 排除后,转化的时候就不会忽略它,从而解决语法报错的问题。

    Ts 类型错误

  •  TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
        src/views/inventory-map/__tests__/available.spec.ts:15:1 - error TS2304: Cannot find name 'beforeEach'.
    
        15 beforeEach(() => {
           ~~~~~~~~~~
        src/views/inventory-map/__tests__/available.spec.ts:19:1 - error TS2593: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.
    
        19 describe('available-inventory-map', () => {
           ~~~~~~~~
        src/views/inventory-map/__tests__/available.spec.ts:20:3 - error TS2593: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.
    
    
    
  • 根据提示需要在 tscofig.json 中添加

  • {
        "compilerOptions": {
        "types": [
          "webpack-env",
          "jest"
        ],
      }
    }
    
  • 测试前的工作

    在编写测试用例前,我们需要 Jest 提供组件实例 vm 和渲染的 DOM 结构。对代码逻辑、页面效果的双重测试保障,那么如何获取到这个业务组件?

    直接引用组件是不行的,因为你的业务组件需要的依赖很多,比如 UI 组件库、工具函数、Vuex 的状态等,所以首先我们需要处理好这些依赖。

    处理依赖

    首先要知道要测试的这个业务组件依赖了哪些东西,全局的依赖可以参照 main.ts 或 main.js 入口文件处,其他可根据组件中的引用来判断。有了依赖后如何在 Jest 中获得组件实例?

    Vue 提供了一个单元测试实用工具库 - Vue Test Utils,编写测试用例的时候可以用到它,首先利用 createLocalVue 创建一个 Vue 的类供你添加组件、混入和安装插件而不会污染全局的 Vue 类, 接着将依赖引用进去。

  • const _localVue = createLocalVue();
    _localVue.use(Vuex);
    _localVue.use(UI);
    _localVue.use(i18nInstall);
    _localVue.component('s-filter', SFilter);
    _localVue.component('w-table', WTable);
    _localVue.directive('xxx', {
      inserted: (el, binding) => {
        ....
      },
    });
    export const localVue = _localVue;
    
    
  • 这样就拿到了一个包含依赖的 Vue 类,接着处理 Vuex,比如我们需要枚举值

  • import enums from './enums';
    export const systemStore = new Vuex.Store({
      actions: {},
      state: {
        enums: {
          systemEnums: enums,
        },
      },
    });
    
    
  • 生成实例和 DOM

    在得到 localVue 和 store 之后,我们要用它去生成结果,通过 mount 将组件渲染出来。

  • import { localVue, systemStore } from '@/utils/unit-test/common';
    import { mount } from '@vue/test-utils';
    require('intersection-observer'); // 兼容jsdom不支持IntersectionObserver
    import TaskList from '../available-inventory-map/index.vue'; // 引用要测试的业务
    let store: any;
    beforeEach(() => {
      store = systemStore;
    });
    
    describe('available-inventory-map', () => {
      it('筛选项测试', () => {
        const renderer = createRenderer();
        const wrapper = mount(TaskList, {
          localVue,
          store,
          attachToDocument: true,
        });
        const html = wrapper.html(); // 得到完整的 html 结构
        const vm = wrapper.vm; // 组件实例
        console.log(html, vm);
      })
    }
    
    
    
  • 将 localVue 和 store,通过 mount 最终得到实例和它的 DOM 结构。接下来就可以根据实例和 DOM 去编写自己的测试用例啦。

    总结

    本文主要介绍了在 Vue + Ts 项目中配置 Jest 自动化测试中遇到的问题总结,介绍基本配置和常见错误的解决方法,以及如何在开始编写测试用例前得到完整的组件信息和 DOM。为接下来的用例编写打下基础。

    引用

    Vue Test Utils

    到此这篇关于Vue-Jest 自动化测试基础配置详解的文章就介绍到这了,更多相关Vue-Jest 自动化测试内容请搜索开心学习网以前的文章或继续浏览下面的相关文章希望大家以后多多支持开心学习网!

    上一篇下一篇

    猜您喜欢

    热门推荐