【问题标题】:"SyntaxError: Cannot use import statement outside a module" when writing test with typescript with lit-html使用带有 lit-html 的打字稿编写测试时出现“语法错误:无法在模块外使用 import 语句”
【发布时间】:2020-09-23 18:55:05
【问题描述】:

我用打字稿写了一个简单的demo 用lit-html:

import {html, TemplateResult} from 'lit-html';

export default function sayHello(name: string): TemplateResult {
  return html`<h1>Hello ${name}</h1>`;
}

并用 jest 写一些简单的测试:

import sayHello from "./sayHello";
import {render} from "lit-html";

beforeEach(() => {
  render('', document.body);
})

describe('sayHello', () => {
  it('says hello', () => {
    render(sayHello('world'), document.body);
    const component = document.querySelector('h1');
    expect(component).toBeDefined();
  })
})

我的“jest.config.js”是:

module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
}

但是当我使用jest 运行测试时,我得到了这样的错误:

FAIL  src/sayHello.test.ts
  ● Test suite failed to run

    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:

    /workspace/typescript-webpack-lit-html-jest-test-demo/node_modules/lit-html/lit-html.js:31
    import { defaultTemplateProcessor } from './lib/default-template-processor.js';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import {html, TemplateResult} from 'lit-html';
        | ^
      2 |
      3 | export default function sayHello(name: string): TemplateResult {
      4 |   return html`<h1>Hello ${name}</h1>`;

      at Runtime._execModule (node_modules/jest-runtime/build/index.js:1166:56)
      at Object.<anonymous> (src/sayHello.ts:1:1)
      at Object.<anonymous> (src/sayHello.test.ts:1:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.339 s
Ran all test suites.
error Command failed with exit code 1.

原因应该是“node_modules”node_modules/lit-html/lit-html.js中的文件使用了es模块,jest处理不好。

我尝试了各种配置,但仍然无法修复,需要您的帮助,谢谢。

针对这个问题的一个小而完整的演示项目:https://github.com/freewind-demos/typescript-webpack-lit-html-jest-test-demo

【问题讨论】:

    标签: typescript jestjs ts-jest lit-html es6-modules


    【解决方案1】:

    默认情况下,Jest 不会转换 /node_modules/ (docs)。为了使其正常工作,您可以像这样更改配置

    点亮 2.0

    还有@lit 命名空间包也需要转换:

    • @lit/reactive-element

    所以在正则表达式中添加可选的@ 就可以了

    jest.config.js

    module.exports = {
      // ...
      transformIgnorePatterns: ["node_modules/(?!\@?lit)"],
    }
    

    working GitHub setup


    ts-jest >27.x

    config: 移除对 tsConfig 选项的支持 (#2127) (3cc9b80)

    应使用小写tsconfig 而不是tsConfig

    jest.config.js

    module.exports = {
      preset: "ts-jest",
      testEnvironment: "jsdom",
      transform: {
        // transform files with ts-jest
        "^.+\\.(js|ts)$": "ts-jest",
      },
      transformIgnorePatterns: [
        // allow lit-html transformation
        "node_modules/(?!lit-html)",
      ],
      globals: {
        "ts-jest": {
          tsconfig: {
            // allow js in typescript
            allowJs: true,
          },
        },
      },
    };
    

    working GitHub setup (with "ts-jest": "27.0.3")


    ts-jest

    jest.config.js

    module.exports = {
      preset: "ts-jest",
      testEnvironment: "jsdom",
      transform: {
        // transform files with ts-jest
        "^.+\\.(js|ts)$": "ts-jest",
      },
      transformIgnorePatterns: [
        // allow lit-html transformation
        "node_modules/(?!lit-html)",
      ],
      globals: {
        "ts-jest": {
          tsConfig: {
            // allow js in typescript
            allowJs: true,
          },
        },
      },
    };
    

    working GitHub setup(修复分支)

    【讨论】:

    • 谢谢!不幸的是,打字稿 4.3.3+ 似乎又出现了错误。
    • @jhorback 用最新版本的解决方案更新了我的答案
    • 不适用于lit
    • 嗨@Teneff,在您的仓库中,您使用的是已弃用的 lit-element。可以关注lit.dev/docs/releases/upgrade升级。
    • @leonheess 看看the lit branch
    猜你喜欢
    • 2020-10-08
    • 2020-05-30
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2021-12-30
    相关资源
    最近更新 更多