Vue2.7.14下的单元测试环境搭建
依赖
vue”: “^2.7.14”,
“@babel/preset-env”: “~7.24.5”,
“babel-core”: “~6.26.3”,
“@vue/compiler-dom”: “~3.4.26”,
“@vue/compiler-dom”: “~3.4.26”,
“@vue/test-utils”: “~1.3.6”,
“babel-jest”: “~29.7.0”,
“babel-preset-env”: “~1.7.0”,
“jest”: “~29.7.0”,
“jest-environment-jsdom”: “~29.7.0”,
“jest-serializer-vue”: “~3.1.0”,
“jest-transform-stub”: “~2.0.0”,
“jsdom”: “16.7.0”,
“vue-jest”: “~3.0.7”,
“vue-server-renderer”: “2.7.16”,
安装依赖:
npm install @babel/preset-env babel-core @vue/compiler-dom @vue/test-utils babel-jest babel-preset-env jest jest-environment-jsdom jest-serializer-vue jest-transform-stub jsdom vue-jest vue-server-renderer
配置步骤
新增/修改.babelrc
配置
{ "presets": [ ["env", { "modules": false }] ], "env": { "test": { "presets": ["env"] } } }
|
建立测试文件夹
根目录下建立test目录,test里面再按照如下建立对应文件
其中jest.conf.js
文件配置:
const path = require('path');
module.exports = { testEnvironment: 'jsdom', verbose: true, testURL: 'http://localhost/', rootDir: path.resolve(__dirname, '../../'), moduleFileExtensions: [ 'js', 'json', 'vue' ], moduleNameMapper: { '^@\/(.*?\.?(js|vue)?|)$': '<rootDir>/src/$1', '\\.(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|scss|sass)$': '<rootDir>/test/unit/__mocks__/styleMock.js' }, testMatch: [ '<rootDir>/test/unit/specs/*.spec.js' ], transform: { '^.+\\.js$': '<rootDir>/node_modules/babel-jest', '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest' }, testPathIgnorePatterns: [ '<rootDir>/test/e2e' ], snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'], coverageDirectory: '<rootDir>/test/unit/coverage', collectCoverageFrom: [ 'src/components/*.(vue)', '!src/main.js', '!src/router/index.js', '!**/node_modules/**' ] }
|
.eslintrc
文件配置;
{ "env": { "jest": true } }
|
__mocks__
文件目录下建立 fileMock.js
,用来处理测试中遇到的静态资源, 内容就一行代码
module.exports = 'test-file-stub';
|
__mocks__
文件目录下建立 axios.js
module.exports = { get: jest.fn(() => Promise.resolve({ status: 200 })) }
|
添加测试命令
在package.json
的 scripts
里添加测试命令
"unit": "jest --config test/unit/jest.conf.js --coverage"
|
如果不需要计算单测覆盖率的话可以去掉--coverage
编写测试用例代码
在specs
下写测试用例代码
eg. HelloWorld.spec.js
import HelloWorld from '@/components/HelloWorld.vue' import { mount } from '@vue/test-utils'
describe('HelloWorld.vue', () => { it('显示默认的问候语', () => { const wrapper = mount(HelloWorld) console.log('VueUtils', wrapper.find('h1').text()) expect(wrapper.find('h1').text()).toBe('Hello, Vue!') })
it('点击按钮后,问候语应该变为"Hola, Vue!"', () => { const wrapper = mount(HelloWorld) wrapper.find('button').trigger('click') expect(wrapper.find('h1').text()).toBe('Hola, Vue!') }) })
|
启动测试
执行 npm run unit
就可以启动测试了