【问题标题】:Cannot use import statement outside a module in Jest Test module无法在 Jest Test 模块中的模块外使用 import 语句
【发布时间】:2020-06-15 07:33:20
【问题描述】:

我是 Jest 的新手。我试图为基本功能编写测试

export const queryValidate = (query) => {
const str = query.replace(/\s+/g, "");
const conditionsArray = [
    str === "",
    str === "{",
    str === "}",
    str === "{}",
];
if (conditionsArray.includes(true)) {
    return true;
} else {
    return false;
}

};

像这样在我的 Jest 测试文件中

import { queryValidate } from "./components/QueryValidate";
console.log(queryValidate("{"));

我收到此错误消息:

从“./components/QueryValidate”导入 { queryValidate };

SyntaxError: Cannot use import statement outside a module

我不明白这是关于 Jest 错误或 React 模块错误。我尝试编写虚拟测试,例如:test("Fake test", () => { expect(true).toBeTruthy(); }); 这是工作 。 有人可以帮我吗?

【问题讨论】:

  • Jest 配置不正确。它应该处理 ES 模块,但它不这样做。该问题不包含有关 Jest 配置的任何信息。
  • 抱歉,我无法理解您的帖子。我在 package.json 中有一个 devDependencies ` "devDependencies": { "jest": "^26.0.1", "nodemon": "^2.0.4", "prettier": "^2.0.5" }`
  • 需要配置 Jest 才能正常工作。 jestjs.io/docs/en/configuration 。如果您使用像 create-react-app 这样的模板,它会提供预制配置,否则您有责任正确配置它。请提供可以重现您的问题的stackoverflow.com/help/mcve,这是 SO 规则所要求的。

标签: reactjs unit-testing jestjs


【解决方案1】:

我没有足够的声誉来添加评论,因此我正在添加答案。不久前我也遇到了同样的问题。 正如 Estus 在评论中提到的,您需要更改 Jest 配置。 你也可以看看babel-jest,然后设置一个 babel 配置文件/.babelrc,以及预设的 env。

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2022-11-17
    • 2021-02-22
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多