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-jestdoesn't resolvesrcURLs 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-jestuses@vue/component-compiler-utilsto compile the template, but URL parsing requires thetransformAssetUrlsoption.vue-jest3.x does not support passing options to@vue/component-compiler-utils, but that now works in 4.0.0-rc.1 via atemplateCompiler.transformAssetUrlsconfig.Even with this URL parsing enabled, Vue CLI configures
jestto 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-jest4: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-jestconfig in a Jest global, settingtemplateCompiler.transformAssetUrls.Modify the merged preset's
transformproperty to use ourmy-jest-url-loadertransform for images. This requires removing other image transforms from the default Jest preset to avoid conflicts.GitHub demo