Testing React component including SVG file by using Jest and tsdx

When we use an SVG file inside a React component, the test will be throwing these error. Solution: use jest-sv […]

広告ここから
広告ここまで

目次

    When we use an SVG file inside a React component, the test will be throwing these error.

      ● Test suite failed to run
    
    Jest encountered an unexpected token
    
    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
    
    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
    
    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
    
    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html
    
    Details:
    
    

    Solution: use jest-svg-transformer to support an SVG file

    Using the jest-svg-transformer library, we can test the React component that using an SVG file.

    % yarn add -D jest-svg-transformer

    If you using tsdx, we can put a new jest.config.js file like this example.

    const {createJestConfig} = require('tsdx/dist/createJestConfig');
    const {paths} = require('tsdx/dist/constants');
    
    const config = createJestConfig(undefined, paths.appRoot)
    config.transform["^.+\\.svg$"] = "jest-svg-transformer"
    module.exports = config;

    The SVG image does not render, but the test does not failed

    The solution is not complete. Because the SVG file does not render on the test.

     PASS  src/components/Copyright/Copyright.spec.tsx
    ● Console
    
      console.error
        Warning: Invalid value for prop `src` on <img> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior 
            at img
            at ImageDigitalcubeLogo
            at a
            at small
            at p
            at footer

    But, we can complete running the test, so I prefer to use the way until finding another solution.

    広告ここから
    広告ここまで

    Random posts

    Home
    Search
    Bookmark