jpkleemans / vite-svg-loader

Vite plugin to load SVG files as Vue components
MIT License
555 stars 59 forks source link

`?url` causes tests to fail #70

Closed xFeXx closed 1 year ago

xFeXx commented 1 year ago

First of all, thank you for your work! It really helped a lot while reworking a whole project with vue3 and vite. While testing with only importing without any prefix I could get it running. But I stumbled across a problem while unit testing my components. I imported a svg in order to use it as a background-image:

import CloudsSvg from '~client/assets/svg/registration_animation_clouds.svg?url'

<div :style="{ backgroundImage: `url(${CloudsSvg})` }" >

In dev and prod build everything runs fine, but the test keeps failing. I tried the approach from here: https://github.com/jpkleemans/vite-svg-loader/issues/35 My jest.config.js looks like this:

const esModules = ['lodash'].join('|')

module.exports = {
  rootDir: process.cwd(),
  displayName: {
    name: 'nodejs',
    color: 'blueBright',
  },
  moduleFileExtensions: ['js', 'json', 'ts', 'tsx'],
  moduleNameMapper: {
    '.+\\.(svg?url)$': '<rootDir>/configs/tests/__mocks__/svgUrlMock.ts',
    '^.*\\.svg$': '<rootDir>/configs/tests/__mocks__/svgMock.vue',
    '^.*\\.scss$': '<rootDir>/configs/tests/__mocks__/scssMock.vue',
    '^~configs(.*)$': '<rootDir>/configs/$1',
    '^~engine(.*)$': '<rootDir>/src/engine/$1',
    '^~client(.*)$': '<rootDir>/src/client/$1',
  },
  setupFiles: ['<rootDir>/configs/tests/utils/setEnvVars.js'],
  setupFilesAfterEnv: [
    '<rootDir>/configs/tests/utils/preload.js',
    '<rootDir>/configs/tests/utils/ignoreWarn.js',
    '<rootDir>/configs/tests/utils/ignoreError.js',
  ],
  testEnvironment: 'node',
  testEnvironmentOptions: {
    customExportConditions: ['node', 'node-addons'],
  },
  testRegex: ['__tests__\\/[A-Za-z_.]*\\.(service|node|redirect)\\.(spec|test)\\.ts?$'],
  transform: {
    '\\.[jt]sx?$': 'babel-jest',
  },
  transformIgnorePatterns: [`<rootDir>/node_modules/(?!(${esModules})/)`],
  verbose: false,
}

I know the problem is '.+\\.(svg?url)$': '<rootDir>/configs/tests/__mocks__/svgUrlMock.ts',, but I can't find a working solution. Is there a clever way to do this, or is it possible to add native jest support? Thanks in advance!

xFeXx commented 1 year ago

Nevermind, I got it running with: '^.*\\.(svg)(\\?url)$': '<rootDir>/configs/tests/__mocks__/svgUrlMock.ts',

svgUrlMock.ts:
export default 'test.svg'
slevinsk21 commented 6 months ago

Hi, I have the same issue but I'm using react.js. Is there any special setting in the "svgrUrlMock.ts" file that you use? thanks a lot...

image
xFeXx commented 1 month ago

My file just a basic export:

export default 'test.svg'