运行下面的命令能够正常进行测试
"test:unit": "jest --clearCache && vue-cli-service test:unit",
但是运行jest
就会提示下面的错误:
FAIL src/tests/unit/index.spec.js
● Test suite failed to run
ReferenceError: sessionStorage is not defined
15 | import Mock from 'mockjs';
16 | import { CONSTANT_PORT_TYPE_LIST, CONSTANT_NODE_TYPE_LIST } from '../components/constant';
> 17 | const storage = sessionStorage;
| ^
18 | export default {
19 | namespaced: true,
20 | state() {
at Object.sessionStorage (src/views/panel/modules/index.js:17:17)
at Object.<anonymous> (src/store/index.js:10:1)
JEST.config配置
const { defaults } = require('jest-config');
module.exports = {
verbose: true,
moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest'
},
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: ['jest-serializer-vue'],
testMatch: [
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],
setupFiles: ['<rootDir>/src/tests/unit/setup'], // 类似 webpack.entry
collectCoverageFrom: [ // 类似 webpack 的 rule.include
'src/**/*.{js,vue}',
'!src/main.js',
'!src/router/index.js',
'!src/store/index.js',
'!**/node_modules/**',
],
coverageDirectory: '<rootDir>/src/tests/unit/coverage',
'collectCoverage': false,
'coverageReporters': [
'lcov',
'text-summary'
],
}
JEST setup文件
import Vue from 'vue';
import _ from 'lodash';
Vue.config.productionTip = false;
如果在setup文件中设置以下,就不会报错,但是会报出其他关键方法或对象不存在
const sessionStorageMock = {
getItem: function () { return "{}" },
setItem: jest.fn(),
clear: jest.fn()
};
global.sessionStorage = sessionStorageMock;
哪位大神有遇到类似问题。
报错如下图所示:
image.png
解决方式:
1,安装Babel转换器: npm install babel-jest @babel/core @babel/preset-env -D
2,在项目根目录下新建一个.babelrc的文件,配置如下所示。
{
"presets": [
[
"@babel/preset-env", {
"targets": {
"node":"current"
}
}
]
]
}
3,再重新执行 =》npm run test
image.png
就可以执行成功了