如何解决“不能在模块外使用 import 语句"?开玩笑 [英] How to resolve "Cannot use import statement outside a module" in jest
问题描述
我有一个使用 TypeScript、Jest、Webpack 和 Babel 构建的 React 应用程序(不使用 Create React App).尝试运行 yarn jest
时,出现以下错误:
I have a React application (not using Create React App) built using TypeScript, Jest, Webpack, and Babel. When trying to run yarn jest
, I get the following error:
我已尝试删除所有软件包并重新添加它们.它不能解决这个问题.我看过类似的问题和文档,但我仍然误解了一些东西.我什至遵循另一个指南从头开始设置此环境,但我的代码仍然收到此问题.
I have tried removing all packages and re-adding them. It does not resolve this. I have looked at similar questions and documentation and I am still misunderstanding something. I went so far as to follow another guide for setting up this environment from scratch and still received this issue with my code.
依赖包括...
"dependencies": {
"@babel/plugin-transform-runtime": "^7.6.2",
"@babel/polyfill": "^7.6.0",
"babel-jest": "^24.9.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.11.0",
"source-map-loader": "^0.2.4"
},
"devDependencies": {
"@babel/core": "^7.6.0",
"@babel/preset-env": "^7.6.0",
"@babel/preset-react": "^7.0.0",
"@types/enzyme": "^3.9.2",
"@types/enzyme-adapter-react-16": "^1.0.5",
"@types/jest": "^24.0.13",
组件的导入行...
import * as React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/pages";
import {
Footer,
Header,
Navigation,
} from "./components/shared";
测试文件....
import * as React from "react";
import * as renderer from "react-test-renderer";
import App from "../App";
it("Renders the Footer correctly", () => {
const tree = renderer
.create(<App />)
.toJSON();
expect(tree).toMatchSnapshot();
});
我希望能够在我的组件中使用命名导入,而不会导致测试失败.如果我只通过我的解决方案使用默认导入,它似乎可以解决问题,但我宁愿不走那条路.
I expected to be able to use named imports in my components without my tests blowing up. It appears to fix the issue if I only use default imports through my solution, but I would prefer to not go that route.
推荐答案
同样使用 Babel、Typescript 和 Jest.有同样的失败,让我疯狂了几个小时.最后为测试创建了一个新的 babel.config.js
文件.有一个大的 .babelrc
,无论我对它做了什么,它都没有被开玩笑捡起.主应用仍然使用 .babelrc
,因为它会覆盖 babel.config.js
文件.
Also using Babel, Typescript and Jest. Had the same failure, driving me crazy for hours.
Ended up creating a new babel.config.js
file specifically for the tests. Had a large .babelrc
that wasn't getting picked up by jest no matter what i did to it. Main app still uses the .babelrc
as this overrides babel.config.js
files.
安装 jest、ts-jest 和 babel-jest:
Install jest, ts-jest and babel-jest:
npm i jest ts-jest babel-jest
babel.config.js
(仅供玩笑使用)
module.exports = {presets: ['@babel/preset-env']}
jest.config.js
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\.(ts|tsx)?$': 'ts-jest',
"^.+\.(js|jsx)$": "babel-jest",
}
};
package.json
"scripts": {
"test": "jest"
这篇关于如何解决“不能在模块外使用 import 语句"?开玩笑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!