搜索

首页  >  问答  >  正文

是否有一种方法可以在Vue模板和脚本中使用别名来映射vue-jest配置?

<p>依赖项: "@vue/cli-plugin-unit-jest": "^4.5.13", "@vue/test-utils": "^1.2.1", "vue-jest": "^3.0.7"</p> <p>我有一个应用程序,在vue.config.js中设置了一个别名(比如说"foo"):</p> <pre class="brush:php;toolbar:false;">module.exports = { chainWebpack: (config) => { // 将项目名称设置为别名 config.resolve.alias.set('foo', __dirname); }, };</pre> <p>对于导入语句和HTML标签的src属性...</p> <p>在main.js中:</p> <pre class="brush:php;toolbar:false;">... import App from 'foo/src/components/core/App'; ...</pre> <p>在../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>我知道我可以在jest.config.js中使用moduleNameMapper,类似于:</p> <p><code>'^foo(.*)$': '<rootDir>$1',</code></p> <p>然而,这不会映射出现在HTML标签的src属性中的别名。有没有办法通过配置设置或其他方式让vue-jest解释这些属性路径呢?</p> <p>非常感谢任何建议。</p>
P粉476547076P粉476547076548 天前546

全部回复(1)我来回复

  • P粉256487077

    P粉2564870772023-08-27 00:35:45

    SFC中的URL解析

    vue-jest无法解析SFC中顶级块标签的src URL,因此您需要在src/components/core/App/index.vue中使用未别名的相对路径:

    1

    2

    3

    <script src="./script.js" />

    <style module src="./style.css" />

    <template src="./template.html" />

    模板内容中的URL解析

    vue-jest使用@vue/component-compiler-utils编译模板,但URL解析需要transformAssetUrls选项vue-jest 3.x不支持向@vue/component-compiler-utils传递选项,但在4.0.0-rc.1中通过templateCompiler.transformAssetUrls配置实现。

    即使启用了URL解析,Vue CLI配置jest返回空字符串以获取require的媒体,包括图像。如果您的测试需要与正常解析的URL一起在生产环境中工作,您将需要一个模仿url-loader的Jest转换器。Vue CLI配置加载器以如果大于4KB,则返回解析的文件名; 否则返回base64数据URL

    要启用URL解析:

    1. 升级到vue-jest 4:

      1

      npm i -D vue-jest@4

    2. 为自定义的my-jest-url-loader创建以下文件,稍后将在下面使用:

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

      21

      22

      23

      24

      25

      26

      // <rootDir>/tests/my-jest-url-loader.js

      const urlLoader = require('url-loader')

       

      module.exports = {

        process(src, filename) {

          const urlLoaderOptions = {

            esModule: false,

            limit: 4096,

            fallback: {

              loader: 'file-loader',

              options: {

                esModule: false,

                emitFile: false,

                name: filename,

              },

            },

          }

          const results = urlLoader.call({

            query: urlLoaderOptions,

            resourcePath: filename,

          }, src)

       

          // strip leading Webpack prefix from file path if it exists

          return results.replace(/^module.exports = __webpack_public_path__ \+ /, 'module.exports = ')

        }

      }

    3. 为了避免意外覆盖Vue CLI的默认Jest预设,使用合并工具(例如lodash.merge)在jest.config.js中插入自定义配置。

    4. Jest全局中添加一个vue-jest配置,设置templateCompiler.transformAssetUrls

    5. 修改合并预设的transform属性,使用我们的my-jest-url-loader转换器来处理图像。这需要从默认Jest预设中删除其他图像转换器,以避免冲突。

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

      21

      22

      23

      24

      25

      26

      27

      28

      29

      30

      31

      32

      33

      34

      35

      36

      37

      38

      39

      40

      41

      42

      43

      44

      45

      46

      // jest.config.js

      const vueJestPreset = require('@vue/cli-plugin-unit-jest/presets/default/jest-preset')

      const merge = require('lodash.merge') 3️⃣

       

      const newJestPreset = merge(vueJestPreset, {

        globals: { 4️⃣

          'vue-jest': {

            templateCompiler: {

              transformAssetUrls: {

                video: ['src', 'poster'],

                source: 'src',

                img: 'src',

                image: ['xlink:href', 'href'],

                use: ['xlink:href', 'href']

              }

            }

          }

        },

        moduleNameMapper: {

          '^foo/(.*)$': '<rootDir>/',

        },

      })

       

      function useUrlLoaderForImages(preset) { 5️⃣

        const imageTypes = ['jpg', 'jpeg', 'png', 'svg', 'gif', 'webp']

        const imageTypesRegex = new RegExp(`(${imageTypes.join('|')})\|?`, 'ig')

       

        // remove the image types from the transforms

        Object.entries(preset.transform).filter(([key]) => {

          const regex = new RegExp(key)

          return imageTypes.some(ext => regex.test(`filename.${ext}`))

        }).forEach(([key, value]) => {

          delete preset.transform[key]

          const newKey = key.replace(imageTypesRegex, '')

          preset.transform[newKey] = value

        })

       

        preset.transform = {

          ...preset.transform,

          [`.+\.(${imageTypes.join('|')})$`]: '<rootDir>/tests/my-jest-url-loader',

        }

      }

       

      useUrlLoaderForImages(newJestPreset)

       

      module.exports = newJestPreset

    GitHub演示

    回复
    0
  • 取消回复