用 Jest 测试单文件组件
1, 安装 Jest 和 vue Test Utils
NPM install --save-dev jest @vue/test-utils
2, 配置 package.JSON
- // package.JSON
- {
- "scripts": {
- "test": "jest"
- }
- }
3, 需要安装和配置 vue-jest 预处理器
NPM install --save-dev vue-jest
4, 在 package.JSON 中创建一个 jest 块或在项目根目录创建 jest.config.JS
- module.exports = {
- moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
- transform: {
- '^.+\\.vue$': 'vue-jest',
- '.+\\.(CSS|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
- 'jest-transform-stub',
- // 为 Jest 配置 Babel
- '^.+\\.jsx?$': 'babel-jest'
- },
- transformIgnorePatterns: ['/node_modules/'],
- // 别名
- moduleNameMapper: {
- '^@/(.*)$': '<rootdir>/src/$1'
- },
- snapshotSerializers: ['jest-serializer-vue'],
- testMatch: [
- '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
- ],
- testURL: 'http://localhost/',
- watchPlugins: [
- 'jest-watch-typeahead/filename',
- 'jest-watch-typeahead/testname'
- ]
- };
错误信息处理
1,babel 解析 es6 出错, 需要配置 babel 预设
> 需要配置安装 @babel/preset-env [babel-preset-env 会有问题]
NPM install --save-dev @babel/preset-env
> 配置 babel.config.JS
- module.exports = {
- presets: [
- // 使可以正常运行 vue 项目,
- '@vue/app',
- [
- '@babel/preset-env',
- {
- modules: false,
- }
- ]
- ],
- env: {
- test: {
- presets: [['@babel/preset-env', { targets: { node: 'current' } }]]
- }
- }
- }
- 2,NPM test
> 清除缓存, 然后再执行测试参考链接
来源: http://www.bubuko.com/infodetail-3261685.html