测试带有开玩笑模块错误的React/打字稿组件

发布于 2025-02-12 19:35:31 字数 1136 浏览 2 评论 0原文

我正在收到错误SyntaxError:在对React/typescript组件上进行简单测试时,无法在模块外使用导入语句,并且不确定在Babel中使用React/Typecript项目中使用模块的最佳方法, webpack和开玩笑。

这是我的babel.config.js:

const isTest = String(process.env.NODE_ENV) === 'test'
const isProd = String(process.env.NODE_ENV) === 'production'

module.exports = {
  presets: [
    ['@babel/preset-env', { modules: isTest ? 'commonjs' : false }], 
    '@babel/preset-typescript',
};

jest.config.js

module.exports = {
  "roots": [
  "<rootDir>/src"
  ],
  "testMatch": [
  "**/__tests__/**/*.+(ts|tsx|js)",
  "**/?(*.)+(spec|test).+(ts|tsx|js)"
  ],
  "transform": {
  "^.+\\.(ts|tsx)$": "ts-jest"
  },
  "moduleFileExtensions": ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  
  }

这是我要运行的简单测试:

import { render } from '@testing-library/react'
import AppRouter from '../router'

test('it works!', () => {
    render(<AppRouter />)
})

请帮助!

解决方案

请确保在jest.config.js文件中检查您的testregex,并使用testenvironment正确设置testEnvironment:“ JSDOR”如果您使用的是ES6模块进行测试。

I am receiving the error SyntaxError: Cannot use import statement outside a module when running a simple test on a React/Typescript component and not sure the best way of using modules in a React/Typescript project with Babel, webpack, and jest.

Here is my babel.config.js :

const isTest = String(process.env.NODE_ENV) === 'test'
const isProd = String(process.env.NODE_ENV) === 'production'

module.exports = {
  presets: [
    ['@babel/preset-env', { modules: isTest ? 'commonjs' : false }], 
    '@babel/preset-typescript',
};

jest.config.js

module.exports = {
  "roots": [
  "<rootDir>/src"
  ],
  "testMatch": [
  "**/__tests__/**/*.+(ts|tsx|js)",
  "**/?(*.)+(spec|test).+(ts|tsx|js)"
  ],
  "transform": {
  "^.+\\.(ts|tsx)
quot;: "ts-jest"
  },
  "moduleFileExtensions": ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  
  }

Here is the simple test I am trying to run:

import { render } from '@testing-library/react'
import AppRouter from '../router'

test('it works!', () => {
    render(<AppRouter />)
})

Please help!

Solution

Be sure to check your testRegex in your jest.config.js file and the testEnvironment is set correctly with testEnvironment: "jsdom" if you are using ES6 modules for testing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文