Jest在每次测试前导入像Vee Validate这样的常见插件



我是Jest的新手,正在用单元测试来测试我的Nuxt JS应用程序。我已经设置了许多测试文件,并且需要将各种逻辑导入到每个测试文件中,例如我的Vee Validate配置。

我已经尝试将它添加到setup.js文件中,并将其包含在setupFilesAfterEnv中,但它没有被包含。

我做错了什么?

测试/单元/设置.js

import Vue from 'vue'
import { ValidationProvider, ValidationObserver, extend, configure, localize } from 'vee-validate'
import * as rules from 'vee-validate/dist/rules';
import en from 'vee-validate/dist/locale/en.json'
const config = {
mode: 'lazy',
classes: {
valid: '',
invalid: 'tw-border-red-500 dark:tw-border-white'
}
}
Object.keys(rules).forEach(rule => {
extend(rule, rules[rule]);
});
configure(config)
// Register it globally
Vue.component('ValidationObserver', ValidationObserver)
Vue.component('ValidationProvider', ValidationProvider)
// // activate the locales
localize({
en
});

我的jest.config.js文件:

module.exports = {
silent: true,
testEnvironment: 'jsdom',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
'^vue$': 'vue/dist/vue.common.js',
},
moduleFileExtensions: ['js', 'vue', 'json'],
transform: {
'^.+\.js$': 'babel-jest',
'.*\.(vue)$': 'vue-jest',
'vee-validate/dist/rules': 'babel-jest'
},
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/**/*.vue',
],
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!vee-validate/dist/rules)',
],
setupFilesAfterEnv: [
'<rootDir>/tests/unit/setup.js'
]
}

我的一个名为LoanAmount的测试文件是:

import { mount } from '@vue/test-utils'
import flushPromises from 'flush-promises';
import LoanAmount from '@/components/Form/Steps/Loan/LoanAmount'
describe('LoanAmount', () => {
test('is a Vue instance', () => {
const wrapper = mount(LoanAmount)
expect(wrapper.vm).toBeTruthy()
})
test('amount is available for value', async () => {
const wrapper = mount(LoanAmount)
await flushPromises()
const amount = wrapper.findAll('.jest__amount-input')
expect(amount.exists()).toBe(true)
})
})

如果我包含tests/unit/setup.js中的所有内容,并包含在我的describe块之上,那么它就可以工作了,但我不能在每个测试文件中重复这一点。

您可以在jest.config.js:中使用setupFiles属性

module.exports = {
rootDir: path.resolve(__dirname, '../../'),
moduleFileExtensions: [
'js',
'json',
'vue'
],
transform: {
'^.+\.js$': 'babel-jest',
'.*\.(vue)$': 'vue-jest',
'.+\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'vee-validate/dist/rules': 'babel-jest'
},
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!(vuetify)|(vue-material-design-icons)|(vee-validate/dist/rules)|(vue-picture-input/PictureInput.vue))'
],
setupFiles: [
'./tests/unit/jest.setup.js'
],
reporters: ['default', 'jest-junit'],
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/**/Application/*.js'
],
testPathIgnorePatterns: [
'<rootDir>/node_modules/',
'<rootDir>/vendor/',
'<rootDir>/web/'
],
coverageThreshold: {
global: {
branches: process.env.COVERAGE_THRESHOLD_GLOBAL_BRANCH || 37,
functions: process.env.COVERAGE_THRESHOLD_GLOBAL_FUNCTIONS || 40,
lines: process.env.COVERAGE_THRESHOLD_GLOBAL_LINES || 50
}
}
}

最新更新