"SyntaxError: Cannot use import statement outside a module" when writing test with typescript with lit-html
Asked Answered
Q

1

9

I use typescript to write a simple demo with lit-html:

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

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

and use jest to write some simple test:

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();
  })
})

My "jest.config.js" is:

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

But when I run the tests with jest, I got such error:

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.

The reason should be the file in "node_modules" node_modules/lit-html/lit-html.js uses es module, and jest can't handle it well.

I tried all kinds of configurations, but still can't fix it, need your help, thanks.

A small and complete demo project for this issue: https://github.com/freewind-demos/typescript-webpack-lit-html-jest-test-demo

Queri answered 4/6, 2020 at 17:20 Comment(0)
W
12

By default Jest doesn't transforms the /node_modules/ (docs). In order to make it work you can change your configuration like this

Lit 2.0

There are @lit namespaced packages that also need to be transformed:

  • @lit/reactive-element

so adding optional @ in the regex does the job

jest.config.js

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

working GitHub setup


ts-jest >27.x

config: remove support for tsConfig option (#2127) (3cc9b80)

lowercase tsconfig should be used instead of 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 <27.x

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 (the fix branch)

Wig answered 5/6, 2020 at 13:50 Comment(6)
Thanks for this! Unfortunately it looks as if the error is back with typescript 4.3.3+.Handpick
@Handpick updated my answer with a solution for the latest versionsWig
Not working for litPeek
Hi @Teneff, in your repo you are using lit-element which is deprecated. You can follow lit.dev/docs/releases/upgrade to upgrade.Peek
@Peek take a look a the lit branchWig
@Wig Only worked after I did: transformIgnorePatterns: [`/node_modules/(?!${['lit-element', 'lit-html', 'lit', '@lit'].join('|')})`] but thank you for the effortPeek

© 2022 - 2024 — McMap. All rights reserved.