testing-library / svelte-testing-library

:chipmunk: Simple and complete Svelte DOM testing utilities that encourage good testing practices
https://testing-library.com/docs/svelte-testing-library/intro
MIT License
615 stars 33 forks source link

Failed to setup jest with Svelte4 and @testing-library/svelte #252

Closed eroncastro closed 6 months ago

eroncastro commented 1 year ago

Hi.

I have followed the setup tutorial with TypeScript to setup Svelte 4 with Jest.

However, I am getting the following error:

node_modules/@testing-library/svelte/src/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { act, cleanup } from './pure.js'

SyntaxError: Cannot use import statement outside a module

      1 | import '@testing-library/jest-dom';
    > 2 | import { render, RenderResult } from '@testing-library/svelte';
        | ^
      3 |
      4 | import HelloWorld from '../../src/components/HelloWorld.svelte';
      5 |

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1496:14)
      at Object.<anonymous> (test/components/HelloAd.test.ts:2:1)    

jest.config.js:

import type { Config } from 'jest';

const config: Config = {
  testEnvironment: 'jsdom',
  globals: {
    window: {},
  },
  collectCoverageFrom: ['src/**/*.{js,ts}'],
  coveragePathIgnorePatterns: ['/node_modules/'],
  transform: {
    '^.+\\.js$': 'babel-jest',
    '^.+\\.ts$': 'ts-jest',
    '^.+\\.svelte$': [
      'svelte-jester',
      {
        'preprocess': true,
      }
    ]
  },
  moduleFileExtensions: [
    'js',
    'ts',
    'svelte'
  ],
  setupFilesAfterEnv: [
    '@testing-library/jest-dom/extend-expect'
  ]
};

export default config;

package.json

"devDependencies": {
    "@babel/preset-env": "^7.22.9",
    "@sveltejs/vite-plugin-svelte": "^2.4.2",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/svelte": "^4.0.3",
    "@testing-library/user-event": "^14.4.3",
    "@tsconfig/svelte": "^5.0.0",
    "babel-jest": "^29.6.1",
    "jest": "^29.6.1",
    "jest-environment-jsdom": "^29.6.1",
    "svelte": "^4.0.5",
    "svelte-check": "^3.4.6",
    "svelte-jester": "^2.3.2",
    "ts-jest": "^29.1.1",
    "ts-node": "^10.9.1",
    "tslib": "^2.6.0",
    "typescript": "^5.0.2",
    "vite": "^4.4.5"
  },
  "volta": {
    "node": "16.20.1",
    "npm": "9.8.1"
  }

Could it be related to the move to ESM?

sebastianrothe commented 1 year ago

Yes, if you want use https://github.com/testing-library/svelte-testing-library/releases/tag/v4.0.0 you need to switch your codebase and testing framework to ESM. Jest has some problems with it. If you have the chance, migrate to Vitest.

Otherwise you can use v3 of this library.

mcous commented 6 months ago

@yanick another one we're good to close out - the Jest setup instructions in the docs have been updated to reflect the required ESM config

yanick commented 6 months ago

Excellent! Closing.