Dependencies: "@vue/cli-plugin-unit-jest": "^4.5.13", "@vue/test-utils": "^1.2.1", "vue-jest": "^3.0.7"
I have an app which uses an alias (say "foo") being set in vue.config.js:
module.exports = {
chainWebpack: (config) => {
// Add project name as alias
config.resolve.alias.set('foo', __dirname);
},
};
For both import statements and HTML tag src...
In main.js:
...
import App from 'foo/src/components/core/App';
...
In ../src/core/App/index.vue:
<script src="foo/src/components/core/App/script.js" />
<style module src="foo/src/components/core/App/style.css" />
<template src="foo/src/components/core/App/template.html" />
I know I can use a moduleNameMapper in jest.config.js, something like:
'^foo(.*)$': '<rootDir>$1',
However, this doesn't map aliases that appear in the src attribute of my HTML tags. Is there any way to have vue-jest interpret these attribute paths via a config setting or some other means?
Any recommendations will be greatly appreciated.
URL parsing in SFCs
vue-jest
doesn't resolvesrc
URLs for the top-level block tags in SFCs, so you'll have to use un-aliased relative paths insrc/components/core/App/index.vue
:URL parsing in
<template>
contentsvue-jest
uses@vue/component-compiler-utils
to compile the template, but URL parsing requires thetransformAssetUrls
option.vue-jest
3.x does not support passing options to@vue/component-compiler-utils
, but that now works in 4.0.0-rc.1 via atemplateCompiler.transformAssetUrls
config.Even with this URL parsing enabled, Vue CLI configures
jest
to return an empty string forrequire
-ed media, including images. If your tests need to work with the normally resolved URLs in production, you'll need a Jest transform that mimicsurl-loader
. Vue CLI configures the loader to return the resolved filename if greater than 4KB; or the base64 data URL otherwise.To enable the URL parsing:
Update to
vue-jest
4:Create the following file for the custom
my-jest-url-loader
, which we'll use later below:To avoid accidentally overwriting Vue CLI's default Jest presets, use a merge utility (e.g.,
lodash.merge
) to insert a custom config injest.config.js
.Add a
vue-jest
config in a Jest global, settingtemplateCompiler.transformAssetUrls
.Modify the merged preset's
transform
property to use ourmy-jest-url-loader
transform for images. This requires removing other image transforms from the default Jest preset to avoid conflicts.GitHub demo