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

时间:2020-02-27 18:20:47

标签: javascript import jestjs

我正在尝试使用测试驱动开发(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,
};

2 个答案:

答案 0 :(得分:0)

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

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

希望这会有所帮助:)

答案 1 :(得分:0)

在您的 package.json 中,使用如下配置可以解决您的问题:

{
    "name": "<blah blah>",
    "version": "1.0.0",
    "description": "",
    "type": "module",
    "scripts": {
        "start": "node server.js",
        "test": "node --experimental-vm-modules node_modules/.bin/jest"
    },
}