beeftony
beeftony

Reputation: 307

SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial

I can't get vue testing to work with vue-test-utils and jest. I created a clean new project with vue cli and added jest as follows, maybe someone can follow along and tell me what I'm doing wrong. (I'm following this installation guide: https://vue-test-utils.vuejs.org/installation/#semantic-versioning)

  1. vue create jest-test

    1.1. npm install

  2. npm install --save-dev jest @vue/test-utils vue-jest

  3. Added jest config to package.json:

    {
      "jest": {
        "moduleFileExtensions": [
          "js",
          "json",
          "vue"
        ],
        "transform": {
          ".*\\.(vue)$": "vue-jest"
        }
      }
    }
    
  4. npm install --save-dev babel-jest @babel/core @babel/preset-env babel-core@^7.0.0-bridge.0

  5. Adjusted jest config to:

    {
      "jest": {
        "transform": {
          // process `*.js` files with `babel-jest`
          ".*\\.(js)$": "babel-jest" //<-- changed this
        }
      }
    }
    
    1. Adjusted babel config to:
    module.exports = {
        presets: [
            '@vue/cli-plugin-babel/preset',
            '@babel/preset-env' //<-- added this
        ]
    };
    
  6. Created example.test.js in a tests directory under the project root (jest-test/tests)

  7. Added the following to this file:

    import { mount } from '@vue/test-utils'
    import HelloWorld from "@/components/HelloWorld";
    
    
    test('displays message', () => {
        const wrapper = mount(HelloWorld)
    
        expect(wrapper.text()).toContain('Welcome to Your Vue.js App')
    })
    
  8. Added the following to the package.json scripts: "jest": "jest"

  9. npm run jest

  10. Get the following error:

    C:\Users\xxx\jest-test\tests\example.test.js:1
        import { mount } from '@vue/test-utils'
        ^^^^^^
    
        SyntaxError: Cannot use import statement outside a module
    

Same happens with Mocha or if I try it in an existing project. Is this a bug? I can't get it working, no matter what I do.

Edit: If I do it with Vue CLI, it works https://vue-test-utils.vuejs.org/installation/#installation-with-vue-cli-recommended

Upvotes: 1

Views: 5977

Answers (1)

Ferry Kranenburg
Ferry Kranenburg

Reputation: 2635

You need to transform both *.vue files and *.js files. I tried your setup and could reproduce the issue. But after altering jest.config.js to the following, the tests will run fine:

module.exports = {
  "moduleFileExtensions": [
    "js",
    "json",
    "vue"
  ],
  transform: {
    '.*\\.js$':'babel-jest',
    ".*\\.(vue)$": "vue-jest"
  },
  moduleNameMapper: {
    "@/(.*)": "<rootDir>/src/$1",
  },
  testEnvironment: 'jsdom'
}

Upvotes: 2

Related Questions