1
1

【React Jest】svgのimportでエラー (Jest encountered an unexpected token)

Posted at

はじめに

Reactの自動テスト、コンポーネント側でsvgをimportしてたのですが、読み込みエラーが出て困ったため記載します

問題

テスト対象のコンポーネントでsvgをimportしてところ以下エラーが発生

 ● Test suite failed to run
                                                    
    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

書いたテスト文

import * as React from 'react';
import App from "../App";
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';

describe("Title Test", () => {
  it("タイトルがHello Jestであること", () => {
    // testId(title)を指定して取得
    render(<App />);
    const title = screen.getByTestId("title");
    expect(title).toHaveTextContent("Hello Jest");
  });
});

原因

jestでは、svgやcssなどのファイルは直接読み込むことができず、mockなどの作成が必要そう

解決方法

モックを作成

// /src/__mock__/SvgMock.jsを作成
// 以下内容
const React = require('react');

const SvgMock = (props) => {
  return React.createElement('svg', props);
};

module.exports = SvgMock;
// jest.config.js修正
export default {
  preset: "ts-jest",
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["./jest.setup.ts"],
  transform: {
    "^.+\\.(ts|tsx)$": "ts-jest",
  },
  moduleNameMapper: {
    "\\.(css|less)$": "identity-obj-proxy",
    "^.+\\.(svg)$": "<rootDir>/src/__mocks__/SvgMock.js"  追加
  },
};

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1