vue jest單元測試環境搭建


溫馨提示:vue-cli3版本已經自帶了jest的單元測試環境。

開始搭建

安裝依賴包

npm install babel-plugin-transform-vue-jsx jest jest-serializer-vue vue-test-utils babel-jest vue-jest

 

創建測試目錄(一般習慣放在項目的根目錄)

mkdir test/unit
cd test/unit

 

創建配置文件

為什么要模擬加載部分靜態文件呢?

因為jest單元測試無需真實加載靜態資源與解析css樣式,jest主要工作是業務邏輯的執行與數據的比對。

const path = require('path');

module.exports = {
    verbose: true,
    testURL: 'http://localhost/',
    rootDir: path.resolve(__dirname, '../../'),
    moduleFileExtensions: [
        'js',
        'json',
        'vue'
    ],
    moduleNameMapper: {
        '^@\/(.*?\.?(js|vue)?|)$': '<rootDir>/src/$1',   # @路徑轉換,例如:@/views/shop/info.vue -> rootDir/src/shop/info.vue
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/test/unit/__mocks__/fileMock.js',   #  模擬加載靜態文件
        '\\.(css|less)$': 'identity-obj-proxy'  # 模擬加載樣式文件 
    },
    testMatch: [
        '<rootDir>/test/unit/**/*.spec.js'
    ],
    transform: {
        '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
        '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest'
    },
    testPathIgnorePatterns: [
        '<rootDir>/test/e2e'
    ],
    setupFiles: ['<rootDir>/test/unit/setup'],
    snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
    coverageDirectory: '<rootDir>/test/unit/coverage',
    collectCoverageFrom: [
        'src/views/**/*.(js|vue)',
        '!src/main.js',
        '!src/router/index.js',
        '!**/node_modules/**'
    ]
};

 

創建腳本命令

# package.json 添加以下運行命令

  "scripts": {
    ...
    "unit": "jest --config test/unit/jest.conf.js --coverage",
  },

 

運行

npm  run unit
報錯:Plugin/Preset files are not allowed to export objects,webpack
該問題由:babel-jest@24.xxx的版本與babel@6.xx的版本不匹配造成的。
解決方法:我們把babel-jest@24.xx版本降為21.0.1就可以了

npm uninstall babel-jest
npm install babel-jest@21.0.1

修改完畢后再次運行
npm run unit

報錯:error:Duplicate declaration "h" # h函數聲明重復
該問題由:.babelrc重復使用了babel-plugin-transform-vue-jsx 造成的
{
  "presets": [
    "stage-3",
    ["env", {
      "modules": false,
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }],
    
  ],
  "plugins": ["transform-vue-jsx","syntax-jsx"],  # 保留這里的transform-vue-jsx
  "env": {
    "test": {
      "presets": ["env", "stage-3"],
      "plugins": ["transform-vue-jsx","transform-es2015-modules-commonjs", "dynamic-import-node"]  # 刪除這里的transform-vue-jsx
    }
  }
}
修改完畢后再次運行
npm run unit

報錯:error:Duplicate declaration "h" # h函數聲明重復
這是babel-plugin-transform-vue-jsx的bug。如果出現這個錯誤建議使用babel-plugin-transform-vue-jsx@3.3.0版本查看詳情
npm uninstall babel-plugin-transform-vue-jsx
npm install babel-plugin-transform-vue-jsx@3.3.0

報錯:Cannot read property 'nodeName' of undefined
這是一般是UI框架組件庫的版本太低,一些組件不支持node環境運行。
簡單粗暴的解決方法:
npm update 更新依賴

修改完畢后再次運行
npm run unit # 完美

 

 
         

 目錄結構:

測試用例:

# seckillActivity.spec.js

import {mount} from 'vue-test-utils'; # API文檔

let test = () => {
    return true;
};
describe('測試', () => {
    it('驗證測試', () => {
        expect(test()).toBe(true);
    });
})
;

靜態文件加載

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM