test-utils icon indicating copy to clipboard operation
test-utils copied to clipboard

"Cannot use import statement outside a module" while using with nuxt-i18n

Open mittalyashu opened this issue 3 years ago • 7 comments

Try running yarn test in https://codesandbox.io/s/optimistic-maxwell-l1dmx?file=/tests/test.spec.js

mittalyashu avatar Jun 23 '21 10:06 mittalyashu

nuxt-i18n is published as ESM module. At the moment Jest needs additional configuration to be able to transpile it.

By default Jest transformers ignore node_modules directory. Jest throws an error, because it sees ESM syntax instead of expected CJS. To solve the issue nuxt-i18n should be included in the transformIgnorePatterns setting of Jest configuration:

transformIgnorePatterns: [
    'node_modules/(?!(nuxt-i18n)/)'
  ]

mrazauskas avatar Jun 24 '21 06:06 mrazauskas

Thanks for the tip!

Having the same issue, but adding the transformIgnorePatterns then takes it to next one as below:

  Details:
  
  node_modules/@nuxtjs/svg-sprite/lib/module.js:1
  ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import fs from 'fs'
  ^^^^^^
  
  SyntaxError: Cannot use import statement outside a module

Adding the following to transformIgnorePatterns doesn't seem to help. It would be great to get some guidance!

'node_modules/.*/(?!(svg-sprite)/)',

sausin avatar Jul 12 '21 11:07 sausin

@sausin Did you try: 'node_modules/(?!(@nuxtjs/svg-sprite)/)'?

Works for me. Does this cause any side effects in your setup?

mrazauskas avatar Jul 12 '21 12:07 mrazauskas

@mrazauskas Thanks for the suggestion. Adding the ignore pattern for svg-sprite lands me back to the error for nuxt-i18n:

  Details:
  
  node_modules/nuxt-i18n/src/index.js:1
  ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { resolve, join } from 'path'
  ^^^^^^
  
  SyntaxError: Cannot use import statement outside a module

This is what the jest.config.js looks like

module.exports = {
  transformIgnorePatterns: [
    'node_modules/(?!(nuxt-i18n)/)',
    'node_modules/(?!(@nuxtjs/svg-sprite)/)',
  ],
  preset: '@nuxt/test-utils',
}

And the test is quite basic at the moment:

import { get, setupTest } from '@nuxt/test-utils'

describe('My test', () => {
  setupTest({
    ssr: false,
  })

  it('renders the index page', async () => {
    const { body } = await get('/')

    expect(body).toContain('<a>A Link</a>')
  })
})

sausin avatar Jul 12 '21 15:07 sausin

Here is the solution for multiple packages (adapted from Jest docs):

transformIgnorePatterns: [
  'node_modules/(?!(@nuxtjs/svg-sprite|nuxt-i18n)/)'
]

mrazauskas avatar Jul 12 '21 16:07 mrazauskas

Awesome, this did the trick - thanks a lot!

sausin avatar Jul 12 '21 17:07 sausin

This works, but translations aren't pulling through. Anyone know how this can be avoided? image

adamchipperfield avatar Oct 01 '21 08:10 adamchipperfield