Is there a way to use aliases in Vue templates and scripts to map vue-jest configuration?
P粉476547076
2023-08-26 17:10:07
<p>Dependencies: "@vue/cli-plugin-unit-jest": "^4.5.13", "@vue/test-utils": "^1.2.1", "vue -jest": "^3.0.7"</p>
<p>I have an application that sets an alias (say "foo") in vue.config.js:</p>
<pre class="brush:php;toolbar:false;">module.exports = {
chainWebpack: (config) => {
//Set the project name as an alias
config.resolve.alias.set('foo', __dirname);
},
};</pre>
<p>For import statements and src attributes of HTML tags...</p>
<p>In main.js:</p>
<pre class="brush:php;toolbar:false;">...
import App from 'foo/src/components/core/App';
...</pre>
<p>In ../src/core/App/index.vue:</p>
<pre class="lang-html prettyprint-override"><code><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" />
</code></pre>
<p>I know I can use moduleNameMapper in jest.config.js, something like:</p>
<p><code>'^foo(.*)$': '<rootDir>$1',</code></p>
<p>However, this does not map aliases that appear in the src attribute of an HTML tag. Is there a way to have vue-jest interpret these property paths through configuration settings or other means? </p>
<p>Any advice is greatly appreciated. </p>
URL parsing in SFC
vue-jest
Thesrc
URL for the top-level block tag in SFC cannot be resolved, so you need to do it insrc/components/core/App/index.vue
Use unaliased relative paths in:URL parsing in template content
jestvue-jest
Use@vue/component-compiler-utils
to compile the template, but URL parsing requirestransformAssetUrls
option.vue-jest
3.x does not support passing options to@vue/component-compiler-utils
, but it does # in #4.0.0-rc.1 ##templateCompiler.transformAssetUrlsConfigurationImplementation.
Even with URL parsing enabled, the Vue CLI configurationto
To enable URL parsing:return an empty string for
require's media, including images. If your tests need to work in production with normally parsed URLs, you will need a Jest converter that mimics
url-loader. The Vue CLI configuration loader returns the parsed filename with
if larger than 4KB; otherwise returns the base64 data URL .Upgrade to- vue-jest
Create the following files for the custom - my-jest-url-loader
To avoid accidentally overwriting the Vue CLI's default Jest presets, use a merge tool (e.g. Add a - vue-jest
Modify the - transform
GitHub Demo4:
that will be used later below:
lodash.merge
) in
jest.config.jsInsert custom configuration.configuration in Jest global and set
templateCompiler.transformAssetUrls
.
property of the merge preset to use our
my-jest-url-loader
converter to process the image. This requires removing other image converters from the default Jest preset to avoid conflicts.