I have problem with testing view when I use image inline in code
'src/assets/icons/circle-small.svg?inline'
I have versions:
- babel-jest: 23.6.0
- vue: 2.6.10
Configuration:
Vue CLI:
const svgRule = config.module.rule('svg');
svgRule.oneOf('inline').use('vue-svg-loader').loader('vue-svg-loader').end();
Jest config:
moduleFileExtensions: [
'js',
'vue',
],
transform: {
'^.+\\.vue$': 'vue-jest',
'^.+\\.js$': '<rootDir>/babel-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg)$': 'jest-transform-stub',
},
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
},
I import in view:
import Img from '#/assets/icons/img.svg?inline';
I getting configuration error:
Could not locate module #/assets/icons/circle-small.svg?inline mapped as:
/some/src/assets/icons/circle-small.svg?inline.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/^#\/(.*)$/": "/some/src/$1"
},
"resolver": null
}
I have a problem with configuring tests for the case when I import inline image. Can anyone know what else i should to configure or what library to use?
I found a solution, it was enough to modify regex
this was wrong:
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg)$': 'jest-transform-stub',
and this is correct:
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)(\\?inline)?$': 'jest-transform-stub',
First, by using jest moduleNameMapper function, remove ?inline
moduleNameMapper: {
'^.+/(.*\\.svg)\\?inline$': '<rootDir>/path/svg/$1'
},
For my case
import SvgBack from '../../assets/svg/back.svg?inline'
(Convert to) --->
import SvgBack from '../../assets/svg/back.svg'
Second, transform the svg files into vuejs format
transform: {
'^.+\\.svg$': '<rootDir>/svgTransform.js',
},
svgTransform.js can find it in the guide https://github.com/visualfanatic/vue-svg-loader/blob/master/docs/faq.md#how-to-use-this-loader-with-jest
jest.config.js
module.exports = {
collectCoverage: false,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/*.vue',
],
// tell Jest to handle `*.vue` files
moduleFileExtensions: [ 'js', 'json', 'vue' ],
moduleNameMapper: {
'^.+/(.*\\.svg)\\?inline$': '<rootDir>/assets/svg/$1',
},
modulePaths: [ '<rootDir>' ],
snapshotSerializers: [ '<rootDir>/node_modules/jest-serializer-vue' ],
transform: {
// process `*.vue` files with `vue-jest`
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
// process js with `babel-jest`
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
// process svg with svgTransform.js
'^.+\\.svg$': '<rootDir>/tests/tools/svgTransform.js',
},
watchman: false,
}
know this thread is very old but got here searching for a solution so will anwser as my solution is a bit different from the other ones and for me simple enough to resolve my problem.
vue: 3.0.0
vue-jest: 5.0.0-0
Just added this config to jest.config.js:
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)(\\?inline)?$': '<rootDir>/tests/mocks/fileMock.js'
}
and added the fileMock.js file:
export default 'test-file-stub'
jest now will load that string and stop give error when I import svg as a component.
This resolves only the error, to check some class on the inline svg the test-file-stub needs to step up for some kind of template, really depends if needed.
Related
I am using Vue 3 + Jest 28.
I've decided do try vue-pdf-embed, which worked great.
The problem is when I run jest.
It says
Inline worker is not supported
With this I can't proceed and got stuck.
My jest.config.ts looks like this:
const esModules = ['quasar', 'quasar/lang', 'lodash-es', 'cnpj'].join('|');
module.exports = {
verbose: true,
testEnvironment: 'jsdom',
testEnvironmentOptions: {
url: 'http://localhost/',
customExportConditions: ['node', 'node-addons'],
},
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tests/tsconfig.json',
isolatedModules: true,
},
},
collectCoverageFrom: ['src/**/*.{vue,js,ts}', '!src/*.{js,ts}', '!**/typings/**', '!src/**/definitions/*.ts'],
coverageProvider: 'v8',
setupFiles: [
'<rootDir>/tests/jest.init.ts',
],
setupFilesAfterEnv: ['<rootDir>/tests/setupTests.ts'],
moduleFileExtensions: [
'vue',
'js',
'ts',
'json',
'jsx',
'tsx',
],
transform: {
// See https://jestjs.io/docs/en/configuration.html#transformignorepatterns-array-string
[`^(${esModules}).+\\.js$`]: 'babel-jest',
'^.+\\.(ts|js|html)$': 'ts-jest',
// vue-jest uses find-babel-file, which searches by this order:
// (async) .babelrc, .babelrc.js, package.json, babel.config.js
// (sync) .babelrc, .babelrc.js, babel.config.js, package.json
// https://github.com/tleunen/find-babel-config/issues/33
'.*\\.vue$': '#vue/vue3-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
},
transformIgnorePatterns: [`node_modules/(?!(${esModules}))`],
moduleNameMapper: {
'#/(.*)$': '<rootDir>/src/$1',
'^quasar$': 'quasar/dist/quasar.esm.prod.js',
'lodash-es': 'lodash',
},
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
};
I've tried so far to add it to the esModules variable I have in my jest config but no success
I came with a reasonable answer: mock the component:
In jest.init.ts, which I refer to in my jest.config.ts above, I put the following:
jest.mock('vue-pdf-embed', () => () => '<mock-vue-pdf-embed/>');
and now everything works just fine ;)
I am trying to build a component library with svelte. I tried to build it with:
npm build
I got the error message:
Plugin typescript: #rollup/plugin-typescript TS2307: Cannot find module './components/MyComponent.svelte' or its corresponding type declarations.
The components I want to export are in the index.tsx:
export { default as MyComponent } from "./components/MyComponent.svelte";
My tsconfig:
{
"extends": "#tsconfig/svelte/tsconfig.json",
"include": ["src/**/*"],
"exclude": ["node_modules/*", "__sapper__/*", "public/*"],
"compilerOptions": {
"target": "es2016",
"module": "esnext",
"outDir": "dist",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"declaration": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"importsNotUsedAsValues": "remove"
}
My rollup.config.js:
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import postcss from 'rollup-plugin-postcss';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import json from '#rollup/plugin-json';
import autoPreprocess from 'svelte-preprocess';
import typescript from '#rollup/plugin-typescript';
import nodeResolve from '#rollup/plugin-node-resolve';
const pkg = require('./package.json');
export default {
input: 'src/index.tsx',
output: [
{
file: pkg.main,
format: 'cjs',
sourcemap: false,
},
{
file: pkg.module,
format: 'esm',
sourcemap: false,
},
],
plugins: [
json({ compact: true }),
svelte({
preprocess: autoPreprocess(),
}),
resolve(),
nodeResolve(),
typescript({ sourceMap: true, rootDir: './src' }),
peerDepsExternal(),
postcss({
extensions: ['.css'],
}),
],
};
Does anyone already had such a problem? Thanks in advance!
You may have to add a type declaration like this:
import type { SvelteComponentTyped } from 'svelte';
declare module '*.svelte' {
export default SvelteComponentTyped;
}
The svelte package also provides something like this via svelte/types/runtime/ambient.d.ts, though it may not be visible to tsc depending on configuration.
Maybe you could also include this file somehow via the tsconfig.json.
jest: 28.1.3,
vue-jest: 3.0.7
vue: 2.7.8
my jest.config.js is:
module.exports = {
clearMocks: true,
collectCoverage: true,
collectCoverageFrom: ['src/**/*.{js,vue}', '!**/node_modules/**'],
transform: {
'^[^.]+.vue$': 'vue-jest',
'^.+\\.js$': 'babel-jest',
'.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'./mocks/fileMock.js',
},
coverageReporters: ['html'],
coverageThreshold: {
global: {
statements: 90,
functions: 90,
branches: 90,
},
},
moduleFileExtensions: ['js', 'vue'],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
},
};
when I use jest --coverage to run jest, I found some vue files not included in coverage reports,
but some vue files is ok, (Sidebar/index.vue is not in, but CommonList/Item.vue is ok):
when compare these vue compoents files, I found that when vue component file has no "import", it did not in coverage reports,
when import anything,
import something:
this vue component file can be report in coveage reports:
so what happened and what should I do ?
I'm using ESM modules with jest and when compiling with angular 12 jest-preset-angular worked great for me by listing #igniteui in the exclusion list. I upgraded to Angular 13, and the Next version of jest-preset-angular, but I can't get it working now. Following the help page I tried to use this:
require('jest-preset-angular/ngcc-jest-processor')
module.exports = {
preset: 'jest-preset-angular/presets/defaults-esm',
moduleFileExtensions: ['ts', 'html', 'js', 'json', 'mjs'],
resolver: 'jest-preset-angular/build/resolvers/ng-jest-resolver.js',
transformIgnorePatterns: [
"node_modules/(?!#igniteui|tslib|.*\\.mjs$)"
],
transform: {
'^.+\\.(ts|js|mjs|html|svg)$': 'jest-preset-angular'
},
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts']
}
When I run jest it says it can't find the igniteui module. This is the jest.config.js I was using with the older version:
require('jest-preset-angular/ngcc-jest-processor')
module.exports = {
preset: 'jest-preset-angular/presets/defaults-esm',
globals: {
'ts-jest': {
useESM: true,
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.html$'
}
},
testTimeout: 20000,
transformIgnorePatterns: [
"node_modules/(?!#igniteui|tslib)"
],
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts']
}
I finally got it working by doing this:
require('jest-preset-angular')
module.exports = {
preset: 'jest-preset-angular/presets/defaults-esm',
transformIgnorePatterns: [
"node_modules/(?!#igniteui|#infragistics|tslib)"
],
moduleFileExtensions: ['ts', 'html', 'js', 'json', 'mjs'],
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts']
}
For those libraries giving you the bad import errors, add them to the transformIgnorePatters. You just need the prefix. So, for example, I'm using #infragistics/igniteui-angular but I only added #infragistics.
when I'm using ...mapState in vue.js, I ran into an error when bundling files with webpack. The error is
Module build failed: SyntaxError: Unexpected token.
I've tried kinds of babel plugins such as stage-0 and transform-object-rest-spread.
Howerver, none seems to be ok for me. Would you please so kind tell me how to solve it?
the source code is
<script type="text/babel">
import { mapState } from 'vuex';
let [a, b, ...other] = [1,2,3,5,7,9]; // this line is ok
console.log(a);
console.log(b);
console.log(other);
export default{
computed:{
localComputed(){
return 10;
},
...mapState({ //this line caused the error
count: state => state.count
})
},
methods: {
increment() {
this.$store.commit('increment');
},
decrement() {
this.$store.commit('decrement');
}
}
}
</script>
and this is the webpack config fragment
{
test: /\.(js|es|es6|jsx)$/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
['react'],
['es2015', {modules: false, loose: true}],
['stage-2']
],
plugins: [
['transform-runtime'],
// https://github.com/JeffreyWay/laravel-mix/issues/76
['transform-object-rest-spread'],
['transform-es2015-destructuring']
],
comments: false,
cacheDirectory: true
}
},
{
loader: 'eslint-loader',
options: {
configFile: eslintConfigPath
}
}
],
exclude: excludeReg
}
I had a similar problem a while ago. As far as I can see, your issue is that your babel-loader does not currently work on .vue files (which is correct as such).
The vue-loader, which handles .vue files, uses babel internally as well, but it won't use webpack's babel-loader config. The easiest way to provide a config for babel in the vue-loader is (unfortunately) creating a separate .babelrc file with your babel config in the root folder of your project:
.babelrc
{
presets: [
["react"],
["es2015", { "modules": false, "loose": true}],
["stage-2"]
],
plugins: [
["transform-runtime"],
["transform-object-rest-spread"],
["transform-es2015-destructuring"]
]
}
Note that .babelrc requires valid JSON.