xrd
xrd

Reputation: 4069

Unable to use jest to test Svelte components which import SCSS from inside node_modules

I'm attempting to add Jest testing to a project which uses svelte-material-ui.

I was following along with this issue on GitHub, but could not get it to work:

https://github.com/hperrin/svelte-material-ui/issues/91

Here is what I did:

npx degit "sveltejs/template-webpack" smui-jest-testing
cd smui-jest-testing
yarn
yarn add svelte-material-ui
yarn add -D @testing-library/svelte
yarn add -D jest
yarn add -D svelte-jester
yarn add -D @testing-library/jest-dom
yarn add -D identity-obj-proxy
yarn add -D @babel/preset-env

I added a component Hello.svelte:

<script>
import { Button } from '@smui/button';
</script>

<Button>
Hi there.
</Button>

I added src/__tests__/App.spec.js like this:

// NOTE: jest-dom adds handy assertions to Jest and it is recommended, but not required.
import '@testing-library/jest-dom/extend-expect'

import { render,
  //fireEvent
} from '@testing-library/svelte'

import Hello from '../Hello.svelte';

test('shows proper heading when rendered', () => {
  const { getByText } = render(Hello)
  expect(getByText('Hi there')).toBeInTheDocument()
})

My jest.config.js is this:

module.exports = {
  moduleFileExtensions: ['js', 'svelte'],
  moduleNameMapper: {
    '^utils(.*)$': '<rootDir>/src/utils$1',
    '\\.(css|less|scss)$': 'identity-obj-proxy',
  },
  transformIgnorePatterns: ['node_modules/(?!(@smui)/)'],
  testPathIgnorePatterns: ['/node_modules/', '/cypress/'],
  setupFilesAfterEnv: [
    // '<rootDir>/jest.setup.js',
    '@testing-library/jest-dom/extend-expect',
  ],
  transform: {
    // '^.+\\.tsx?$': 'ts-jest',
    '^.+\\.js$': 'babel-jest',
    '^.+\\.svelte$': ['svelte-jester', { preprocess: false }],
  },
  collectCoverageFrom: [
    '!./src/client.js',
    '!./src/server.js',
    '!./src/service-worker.js',
    './src/**/*.svelte',
    './src/**/*.ts',
    './src/**/*.js',
  ],
};

My package.json looks like this in the end:

{
  "name": "svelte-app",
  "version": "1.0.0",
  "devDependencies": {
    "@babel/preset-env": "^7.8.7",
    "@testing-library/jest-dom": "^5.1.1",
    "@testing-library/svelte": "^1.11.0",
    "cross-env": "^5.2.0",
    "css-loader": "^2.1.1",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^25.1.0",
    "mini-css-extract-plugin": "^0.6.0",
    "serve": "^11.0.0",
    "style-loader": "^0.23.1",
    "svelte": "^3.0.0",
    "svelte-jester": "^1.0.5",
    "svelte-loader": "2.13.3",
    "webpack": "^4.30.0",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.3.1"
  },
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack",
    "dev": "webpack-dev-server --content-base public",
    "test": "jest src",
    "test:watch": "npm run test -- --watch"
  },
  "jest": {
    "transform": {
      "^.+\\.svelte$": "svelte-jester"
    },
    "moduleFileExtensions": [
      "js",
      "svelte"
    ],
    "setupFilesAfterEnv": [
      "@testing-library/jest-dom/extend-expect"
    ]
  },
  "dependencies": {
    "svelte-material-ui": "^1.0.0-beta.20"
  }
}

I have a .babelrc.json with this in it:

{
  "presets": [["@babel/preset-env", { "targets": { "node": "current" } }]]
}

When I run yarn test I see this:

$ yarn test
yarn run v1.19.1
warning package.json: No license field
$ jest src
 FAIL  src/__tests__/App.spec.js
  ● 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:

    /home/chrisdawson/Projects/.../javascript-overlay/smui-jest-testing/node_modules/@smui/button/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import './_index.scss';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | <script>
      2 | 
    > 3 | import { Button } from '@smui/button';
        |                ^
      4 | </script>
      5 | 
      6 | <Button>

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1059:14)
      at Object.<anonymous> (src/Hello.svelte:3:16)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.941s
Ran all test suites matching /src/i.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Anything standout here?

Upvotes: 1

Views: 2635

Answers (1)

rixo
rixo

Reputation: 25031

I'm illiterate with Jest, Babel, etc. so don't ask me why, but you should rename your .babelrc.json to babel.config.js, and export your config from this file:

module.exports = {
  presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
}

Your error message looks like files from smui, under node_modules, are not being transpiled (hence ending with an import in the middle of a iife, which is forbidden even in ES6), and so I found this comment providing a solution.

Next, Button is the default export of @smui/button, so change:

import { Button } from '@smui/button';

to:

import Button from '@smui/button';

This one, I'm sure you would have found by yourself.

So the last one before seeing a green mark, I'll leave for you to find ;)

Upvotes: 2

Related Questions