Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
ajkl2533 opened this issue Jul 1, 2020 · 19 comments

Comments

@ajkl2533
Copy link
Contributor

ajkl2533 commented Jul 1, 2020

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 
@stale
Copy link

stale bot commented Jul 25, 2020

Hi everyone! Seems like there hasn't been much going on in this issue lately. If there are still questions, comments, or bugs, please feel free to continue the discussion. Unfortunately, we don't have time to get to every issue. We are always open to contributions so please send us a pull request if you would like to help. Inactive issues will be closed after 30 days. Thanks!

@stale stale bot added the inactive label Jul 25, 2020
@ajkl2533
Copy link
Contributor Author

@shilman Any update on this?

@stale stale bot removed the inactive label Jul 28, 2020
@stale
Copy link

stale bot commented Aug 22, 2020

Hi everyone! Seems like there hasn't been much going on in this issue lately. If there are still questions, comments, or bugs, please feel free to continue the discussion. Unfortunately, we don't have time to get to every issue. We are always open to contributions so please send us a pull request if you would like to help. Inactive issues will be closed after 30 days. Thanks!

@stale stale bot added the inactive label Aug 22, 2020
@stale stale bot removed the inactive label Sep 23, 2020
@shilman shilman added the P3 label Sep 24, 2020
@shilman
Copy link
Member

shilman commented Sep 24, 2020

Nope, would appreciate if someone else can take a look. @Hypnosphi do you have any ideas?

@Hypnosphi
Copy link
Member

@ajkl2533 you also need babel-jest: https://github.com/storybookjs/storybook/tree/next/addons/docs#installation

@bogdanorzea
Copy link

I have the same problem when running Jest after enabling the storyshot addon. It can also be reproduced on the 'sb init' project.

@topcheese
Copy link

topcheese commented Nov 3, 2020

I just discovered this project, so I pretty much don't know what I'm doing. I got this error because my .babel file wasn't in the root directory of the project. I know nothing about Babel, but I'd make sure that's straight.
I'm trying to follow along with the Svelte /SBV6 tutorials.

@miguelangeltorresfp
Copy link

@ajkl2533 Did you get this to work with ts-jest ?

@oxilor
Copy link

oxilor commented 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',
  },
};

@cherylcarpenter
Copy link

@oxilor this did not fix for me :(

@kylemh
Copy link
Member

kylemh commented Jul 13, 2021

So we can't use ts-jest? I wouldn't consider TSDX an active project anymore, but a lot of people obviously still use it and are stuck with ts-jest @shilman

@oxilor
Copy link

oxilor commented Jul 13, 2021

I have the latest version of the Storybook and this way still works.

@kylemh
Copy link
Member

kylemh commented Jul 13, 2021

It appears #13478 was my actual problem.

@oxilor
Copy link

oxilor commented Jul 14, 2021

I created a repo with configuration that works for me, but in this project storyshots started to include Storybook's stories from node_modules. In my real project it works nice. Unfortunately, I don't have time to deal with this problem. If someone knows how to fix it, let me know.

@jeremyzilar
Copy link

The config that @oxilor shared seems to work 🤞
also ensure the your packages are up to date!

@K3TH3R
Copy link

K3TH3R commented Jun 8, 2022

My repo's setup to use CSF for Stories with MDX for docs. Because my MDX is only for docs, I don't actually need the MDX for my unit tests so I can just tell Jest to throw it away:

jest.config.js

module.exports = {
  moduleNameMapper: {
    '\\.mdx?$': '<rootDir/__mocks__/mdxMock.js',
  }
}

mocks/mdxMock.js

module.exports = {}

@shilman shilman removed the P3 label Oct 18, 2022
@ndelangen
Copy link
Member

The future of storyshots is the test-runner:
https://storybook.js.org/docs/react/writing-tests/test-runner#page-top

And use the play function for expectations:
https://storybook.js.org/docs/react/writing-stories/play-function#page-top

We will not be making any improvement / changes to storyshots.

@squidjam
Copy link

squidjam commented May 9, 2023

We will not be making any improvement / changes to storyshots.

As a suggestion, if this is how it will go forward, please update the documentation on your website, as it states that Snapshots is an alternative to Chromatic.

For a self-managed alternative to Chromatic, we offer StoryShots. It allows you to run visual tests on stories by integrating with jest-image-snapshot.

It will be simpler and we won't need to invest time to try and implement it only to have it not work and spend a couple of hours trying to find a solution on search engines.

Also, perhaps you can add a notice to the README on Storyshots and archive the repo.

@ricovitch
Copy link

@ndelangen what about puppeteer integration for visual regression snapshots ? Will it be supported by test-runner approach ? We currently use @storybook/addon-storyshots-puppeteer for the job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests