簡體   English   中英

使用 jest、react、webpack 和 svg 進行測試時出現問題

[英]Problem with tests using jest, react, webpack and svg

我開始使用 react 開發,但我無法使用 svg 文件成功運行測試。

代碼在我的 github repo https://github.com/alejomongua/react-playground中。

運行npm run test時出現此錯誤:


> reactapp@0.1.0 test /home/liliam/Alejo/react-playground
> jest

 FAIL  src/App.test.js
  ● 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:

    /home/liliam/Alejo/react-playground/src/logo.svg:1
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
    ^

    SyntaxError: Unexpected token '<'

      1 | import React from 'react';
    > 2 | import logo from './logo.svg';
        | ^
      3 | import './App.css';
      4 | 
      5 | function App() {

      at Runtime._execModule (node_modules/jest-runtime/build/index.js:1166:56)
      at Object.<anonymous> (src/App.js:2:1)
      at Object.<anonymous> (src/App.test.js:3:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.441 s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! reactapp@0.1.0 test: `jest`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the reactapp@0.1.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/liliam/.npm/_logs/2020-06-22T21_28_24_324Z-debug.log

當我運行npm run dev時,我沒有收到任何錯誤,並且我的應用程序執行了它應該執行的操作。 我錯過了什么?

編輯

這是重現它的方法:

package.js

{
  "name": "mre2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "npx webpack-dev-server --config webpack.config.babel.js",
    "test": "npx jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.10.3",
    "@babel/preset-env": "^7.10.3",
    "@babel/preset-react": "^7.10.1",
    "@babel/register": "^7.10.3",
    "@testing-library/react": "^10.3.0",
    "babel-loader": "^8.1.0",
    "file-loader": "^6.0.0",
    "html-webpack-plugin": "^4.3.0",
    "jest": "^26.0.1",
    "path": "^0.12.7",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  },
  "dependencies": {
    "react": "^16.13.1",
    "react-dom": "^16.13.1"
  }
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

應用程序.js

import React from 'react';
import logo from './logo.svg';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

應用程序.test.js

import React from 'react';
import { render } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
  const { getByText } = render(<App />);
  const linkElement = getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

babel.config.js

module.exports = {
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}

webpack.config.babel.js

import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';

export default {
  entry: './index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        },
      },
      {
        test: /\.svg$/,
        use: 'file-loader'
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin({
    "templateContent": '<!doctype html><html><head><meta charset="utf-8"><title>Webpack App</title><meta name="viewport" content="width=device-width,initial-scale=1"></head><body id="root"><script src="main.js"></script></body></html>'
  })],
  resolve: {
    extensions: [
      '.js'
    ]
  }
};

src/logo.svg文件中,需要將 svg 項導出為 React 組件:

const icon = () => (
    <svg viewBox="0 0 841.9 595.3">
    // your svg content
    </svg>
)

export default icon

此外,您需要將文件重命名為以jsjsx (例如logo.jsx )並更新您在App.js中的導入,以便使用您當前的 jest 和 webpack 配置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM