开玩笑说不能导入模块外部

问题描述 投票:0回答:1

我正在尝试使用测试驱动开发(TDD)进行一些功能

我正在用JavaScript编写。

checkTransparency(urlString)maketransparent(urlString)我正在尝试测试和开发我的两个功能,它们位于一个名为transcript.js的文件中。这些使用inkscape和graphicsmagick npm。我检查了checkTransparent在我的其他项目中的工作情况,但我试图确保可以将这个transparent.js复制粘贴到另一个项目中,并在其他地方使用它。

我的项目文件夹结构如下:

+ node_modules
+ src
--- transparent.js
+ test
--- transparent.spec.js
+ package.json
+ package-lock.json
+ jest.config.js

我使用笑话作为测试框架。问题是我开玩笑(或npm测试)时我得到以下信息:

失败测试/transparent.spec.js●测试套件无法运行]

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:

\\..............\transparent\test\transparent.spec.js:4 <FEW DETAILS OMITTED HERE DELIBERATELY>
import { checkTransparency, makeTransparent } from "../src/transparent"; // const transparent = require("../src/transparent");
^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime._execModule (C:/Users/Kjeong/AppData/Local/Yarn/Data/global/node_modules/jest-runtime/build/index.js:988:58)

测试套件:1个失败,总共1个测试:总计0快照:共0个时间:0.862秒运行所有测试套件。

我的jest.config.js:

module.exports = {
  testEnvironment: "node",
  moduleDirectories: ["node_modules", "src", "transparent"],
  moduleFileExtensions: [
    "js",
    "json",
    "jsx",
    "ts",
    "tsx",
    "node"
  ],
  clearMocks: true,

}

我尝试了以下导出以使此功能正常工作:

export function checkTransparency(urlString) { ... }
export function makeTransparent(urlString) {... }
module.exports = {
     checkTransparency: checkTransparency,
     makeTransparent: makeTransparent,
};
javascript import jest
1个回答
0
投票

如果您确实要使用import关键字,则可能需要遵循these explanations。否则,为什么不只是require

const { checkTransparency, makeTransparent } = require('../src/transparent')

希望这会有所帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.