te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Babel and Jest configuration: SyntaxError: Cannot use import statement outside a module - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Babel and Jest configuration: SyntaxError: Cannot use import statement outside a module - Stack Overflow

programmeradmin4浏览0评论

I'm working on a Ruby on Rails 7 app with a few JS web ponents written using lit element. I'm trying to add Jest to the project so we can unit test our web ponents.

Not using Typescript, just vanilla JS. I'm running node v18.12.1, npm v9.2.0.

I followed the initial Jest getting started steps from their site:

npm install --save-dev jest

Then added "scripts": { "test": "jest" } to package.json.

I created a simple test to try it out and it passed without error.

However, once I added a test for one of my custom web ponents that imports lit (import {LitElement} from 'lit';), I got the following error:

Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see  for how to enable it.
     • If you are trying to use TypeScript, see 
     • 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:
    
    For information about custom transformations, see:
    

    Details:

    /home/app/service/app/javascript/test/utils/validators.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { IsNumber } from '../../utils/validators.js';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1495:14)

Reading the error (and checking here and with Dr Google) it sounded like using Babel was the way to go. So, I went to the Babel installation page for jest and followed their instructions:

npm install --save-dev babel-jest

Then added to package.json:

  "jest": {
    "transform": {
      "^.+\\.[t|j]sx?$": "babel-jest"
    }
  },
}

Then installed babel preset env:

npm install @babel/preset-env --save-dev

And add babel.config.json:

{
  "presets": ["@babel/preset-env"]
}

I continue to get the same error.

My package.json:

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\\.[t|j]sx?$": "babel-jest"
    }
  },
  "devDependencies": {
    "@babel/preset-env": "^7.20.2",
    "babel-jest": "^29.4.3",
    "jest": "^29.4.3",
    "lit": "^2.6.1"
  }
}

My babel.config.json:

{
  "presets": ["@babel/preset-env"]
}

Failing test:

import {SomeFunction} from '/a-valid-path/my-custom.js';

describe('some tests', () => {
  test('a test', () => {
    expect(SomeFunction(some-value)).toBe(true);
  });
});

There are other posts on this issue here on stack overflow. The solutions provided all seem to indicate I need to add some transform and transformIgnorePatterns settings to my jest configuration in package.json (or jest.config.js for those with a separate jest config file) in order to get the transpilation right.

For example here the remended solution was:

"transform": {
      "node_modules/variables/.+\\.(j|t)sx?$": "ts-jest" //I swapped in 'babel-jest' here
    },
    "transformIgnorePatterns": [
      "node_modules/(?!variables/.*)"
    ]

And here it was

  transform: {
    "^.+\\.(js|ts)$": "ts-jest",
  },
  transformIgnorePatterns: [
    "node_modules/(?!lit-html)",
  ],

Here the solution was to add "type": "module" to package.json.

None of these or other solutions I've found here or on other sites have worked. I keep getting the same error.

Does anyone out there know what I'm missing?

I'm working on a Ruby on Rails 7 app with a few JS web ponents written using lit element. I'm trying to add Jest to the project so we can unit test our web ponents.

Not using Typescript, just vanilla JS. I'm running node v18.12.1, npm v9.2.0.

I followed the initial Jest getting started steps from their site:

npm install --save-dev jest

Then added "scripts": { "test": "jest" } to package.json.

I created a simple test to try it out and it passed without error.

However, once I added a test for one of my custom web ponents that imports lit (import {LitElement} from 'lit';), I got the following error:

Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • 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/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /home/app/service/app/javascript/test/utils/validators.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { IsNumber } from '../../utils/validators.js';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1495:14)

Reading the error (and checking here and with Dr Google) it sounded like using Babel was the way to go. So, I went to the Babel installation page for jest and followed their instructions:

npm install --save-dev babel-jest

Then added to package.json:

  "jest": {
    "transform": {
      "^.+\\.[t|j]sx?$": "babel-jest"
    }
  },
}

Then installed babel preset env:

npm install @babel/preset-env --save-dev

And add babel.config.json:

{
  "presets": ["@babel/preset-env"]
}

I continue to get the same error.

My package.json:

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\\.[t|j]sx?$": "babel-jest"
    }
  },
  "devDependencies": {
    "@babel/preset-env": "^7.20.2",
    "babel-jest": "^29.4.3",
    "jest": "^29.4.3",
    "lit": "^2.6.1"
  }
}

My babel.config.json:

{
  "presets": ["@babel/preset-env"]
}

Failing test:

import {SomeFunction} from '/a-valid-path/my-custom.js';

describe('some tests', () => {
  test('a test', () => {
    expect(SomeFunction(some-value)).toBe(true);
  });
});

There are other posts on this issue here on stack overflow. The solutions provided all seem to indicate I need to add some transform and transformIgnorePatterns settings to my jest configuration in package.json (or jest.config.js for those with a separate jest config file) in order to get the transpilation right.

For example here the remended solution was:

"transform": {
      "node_modules/variables/.+\\.(j|t)sx?$": "ts-jest" //I swapped in 'babel-jest' here
    },
    "transformIgnorePatterns": [
      "node_modules/(?!variables/.*)"
    ]

And here it was

  transform: {
    "^.+\\.(js|ts)$": "ts-jest",
  },
  transformIgnorePatterns: [
    "node_modules/(?!lit-html)",
  ],

Here the solution was to add "type": "module" to package.json.

None of these or other solutions I've found here or on other sites have worked. I keep getting the same error.

Does anyone out there know what I'm missing?

Share Improve this question asked Feb 24, 2023 at 23:23 lifeofbrianlifeofbrian 1811 gold badge1 silver badge6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 12

It took some more trial and error, but I eventually resolved it by setting: "transformIgnorePatterns": [] in package.json.

It appears that setting has to be present even though I'm not giving it a value. Removing transformIgnorePatterns entirely results in the same error.

Final working configuration:

Package.json:

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\\.(js|ts)$": "babel-jest"
    },
    "transformIgnorePatterns": []
  },
  "devDependencies": {
    "@babel/preset-env": "^7.20.2",
    "babel-jest": "^29.4.3",
    "jest": "^29.4.3",
    "lit": "^2.6.1"
  }
}

Babel.config.json:

{
  "presets": ["@babel/preset-env"]
}

I had the exact same problem, but with the url-exist dependency instead.

Tried everything under the sun (including your solution), nothing was working, until I realised that the problem was in the way I was mocking the module in my unit test.

I tried the automatic mock as per Jest docs:

import urlExist from "url-exist";

jest.mock("url-exist"); // WRONG, Jest will plain

The issue was finally solved once I added the moduleFactory parameter:

import urlExist from "url-exist";

jest.mock("url-exist", () => jest.fn()); // Working now, phew

I had a similar problem. Jest started working for JS tests using ES Module imports / exports after install babel-jest and define the babel.config in my package.json

npm install --save-dev babel-jest

The package.json

{
  "scripts": {
    "test" : "jest"
  },      
  "jest": {
    "transform": {"^.+\\.jsx?$": "babel-jest"},
    "testEnvironment": "node"
  },
  "babel": {
    "presets": ["@babel/preset-env"]
  },
  "devDependencies": {
    "babel-jest": "^29.7.0"
  },
  "type": "module"
}

However, the VS Code extension Jest and Jest Runner still kept getting the ES module import error

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论