question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Getting "Cannot use import statement outside a module" with MDX files running with Jest

See original GitHub issue

Describe the bug When I add MDX documentation files into my Storybook and run Storyshots with Jest I’m getting SyntaxError: Cannot use import statement outside a module for each of loaded MDX.

Expected behavior Console should be without errors

Code snippets

console.warn
    Unexpected error: SyntaxError: Cannot use import statement outside a module

      at Object.warn (node_modules/@storybook/client-logger/dist/index.js:53:73)
      at node_modules/@storybook/core/dist/client/preview/loadCsf.js:110:34
          at Array.forEach (<anonymous>)
      at node_modules/@storybook/core/dist/client/preview/loadCsf.js:103:20
          at Array.forEach (<anonymous>)
      at node_modules/@storybook/core/dist/client/preview/loadCsf.js:102:12
      at ConfigApi.configure (node_modules/@storybook/client-api/dist/config_api.js:27:7)
//jest.config.js

module.exports = {
  roots: ['./src'],
  setupFilesAfterEnv: ['./jest.setup.ts'],
  moduleFileExtensions: ['js', 'ts', 'tsx', 'json'],
  testPathIgnorePatterns: ['node_modules/'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
    '^.+\\.mdx?$': '@storybook/addon-docs/jest-transform-mdx',
  },
  testMatch: ['./**/*.(test).(ts|tsx)'],
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      'identity-obj-proxy',
  },
};
// main.ts

module.exports = {
  stories: ['../src/**/*.stories.@(tsx|jsx|mdx)'],
  addons: ['@storybook/addon-actions', '@storybook/addon-docs'],
  typescript: {
    check: false,
    checkOptions: {},
    reactDocgen: 'react-docgen-typescript',
    reactDocgenTypescriptOptions: {
      shouldExtractLiteralValuesFromEnum: true,
      propFilter: (prop) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),
    },
  },
};
//storyshots/jest.config.js

/* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path');
const { mergeRight } = require('ramda');
const globalJestConfig = require('../jest.config');
/* eslint-enable */

const storyshotsJestConfig = {
  rootDir: path.join(__dirname, '..'),
  roots: ['./storyshots'],
  testMatch: ['./**/storyshots.runner.ts'],
};

module.exports = mergeRight(globalJestConfig, storyshotsJestConfig);
// storyshots/storyshots.runner.ts
import path from 'path';
import initStoryshots from '@storybook/addon-storyshots';
import { imageSnapshot } from '@storybook/addon-storyshots-puppeteer';

const pathToStorybookStatic = path.join(__dirname, '../storybook-static');

const beforeScreenshot = () => {
  return new Promise(
    (resolve) =>
      setTimeout(() => {
        resolve();
      }, 1000), // sometimes text doesn't render in time, so we wait one second for each image
  );
};

initStoryshots({
  suite: 'Image snapshots',
  storyNameRegex: /^((?!.*?DontTest).)*$/,
  framework: 'react',
  configPath: path.join(__dirname, '../.storybook'),
  test: imageSnapshot({
    beforeScreenshot,
    storybookUrl:
      process.env.CI === 'true'
        ? `file://${pathToStorybookStatic}`
        : `http://host.docker.internal:6006`,
    getMatchOptions: () => ({
      failureThreshold: 0.0,
      failureThresholdType: 'percent',
    }),
  }),
});

System:

System:
    OS: macOS 10.15.4
    CPU: (12) x64 Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
  Binaries:
    Node: 12.13.1 - ~/.nvm/versions/node/v12.13.1/bin/node
    Yarn: 1.22.4 - /usr/local/bin/yarn
    npm: 6.14.5 - ~/Documents/PROJECTS/ambrosia-design-system/node_modules/.bin/npm
  Browsers:
    Chrome: 83.0.4103.116
    Safari: 13.1
  npmPackages:
    @storybook/addon-actions: ^6.0.0-beta.36 => 6.0.0-beta.37 
    @storybook/addon-docs: ^6.0.0-beta.36 => 6.0.0-beta.37 
    @storybook/addon-storyshots: ^6.0.0-beta.36 => 6.0.0-beta.37 
    @storybook/addon-storyshots-puppeteer: ^6.0.0-beta.36 => 6.0.0-beta.37 
    @storybook/react: ^6.0.0-beta.36 => 6.0.0-beta.37 
    @storybook/theming: ^6.0.0-beta.36 => 6.0.0-beta.37 

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:11
  • Comments:16 (5 by maintainers)

github_iconTop GitHub Comments

6reactions
oxilorcommented, Jan 10, 2021

I replaced ts-jest to babel-jest and the error was disappear.

1. Install the babel

yarn add -D babel-jest @babel/preset-env @babel/preset-react @babel/preset-typescript

2. Create the jest.transform.js file

module.exports = require('babel-jest').createTransformer({
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          esmodules: true,
        },
      },
    ],
    '@babel/preset-react',
    '@babel/preset-typescript',
  ],
});

3. Add transform to your jest.config.js

module.exports = {
  testEnvironment: 'jsdom',
  transform: {
    '^.+\\.[tj]sx?$': './jest.transform.js',
    '^.+\\.mdx?$': '@storybook/addon-docs/jest-transform-mdx',
  },
};
6reactions
ajkl2533commented, Jul 28, 2020

@shilman Any update on this?

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to resolve "Cannot use import statement outside a ...
FYI, I was running into this when setting up a custom TestSequencer for Jest and I just switched to using require instead of...
Read more >
Jest and ESM: Cannot use import statement outside a module
Jest and ESM: Cannot use import statement outside a module. This post describes a fix for a common issue with Jest and ESM...
Read more >
SyntaxError: Cannot use import statement outside a module ...
The main reason behind getting this error is that we have used the ES6 feature for importing our module but our NodeJS package.json...
Read more >
Getting started - MDX
It shows how to use MDX with your bundler and JSX runtime of choice. ... If you want to import MDX files in...
Read more >
JavaScript - Parcel
The import statement can be used to reference a value exposed by the export ... scope cannot be accessed outside the module unless...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found