Niaz Estefaie
Niaz Estefaie

Reputation: 577

Using jest and vue throw SyntaxError: Unexpected identifier error for import

I'm new to jest and I'm using vue3 and jest 26.6.3 in my project

//pachage.json

"jest": {
  "moduleFileExtensions": [
    "js",
    "json",
    "vue"
  ],
  "moduleNameMapper": {
    "^@/(.*)$": "<rootDir>/src/$1",
    "^vue$": "vue/dist/vue.common.js"
  },
  "transform": {
    ".*\\.(vue)$": "<rootDir>/jest/jest-vue",
    ".*": "babel-jest"
  }
},

I create a jest-vue file and the content is

// jest/jest-vue.js

const templateRegex = /<template>([\s\S]*)<\/template>/gm;
const scriptRegex = /<script>([\s\S]*)<\/script>/gm;
const babelJest = require("babel-jest");

module.exports = {
  process(src, filepath, config, transformOptions) {
    templateRegex.lastIndex = scriptRegex.lastIndex = 0;
    const template = templateRegex.exec(src)[1];
    return `${babelJest.process(
      scriptRegex.exec(src)[1],
      filepath + ".js",
      config,
      transformOptions
    )};
        exports.default['template']=\`${template}\`;
        `;
  },
};

// app.spec.js

import App from "@/App.vue";

describe('App', () => {
  // Inspect the raw component options
  it("has data", () => {
    expect(typeof App.data).toBe("function");
  });
});

after I run yarn test I'm getting this error

({"Object.":function(module,exports,require,__dirname,__filename,global,jest){[object Object];

SyntaxError: Unexpected identifier

> 1 | import App from "@/App.vue";

if you need to see my code here is the github repo

Upvotes: 0

Views: 96

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

I think the jest is missing the connection with Vue.

try installing vue-jest, Must include @next

yarn add vue-jest@next

using vue-test to do the code transformation of .vue file

"jest": {
    "moduleFileExtensions": [
        "js",
        "json",
        "vue"
    ],
    "moduleNameMapper": {
        "^@/(.*)$": "<rootDir>/src/$1"
    },
    "transform": {
        "^.+\\.vue$": "vue-jest", 
        "^.+\\.js$": "babel-jest"
    }
},

and you should be good to go

Upvotes: 1

Related Questions