(JEST/VueJS) Cannot use import statement outside a module - vue.js

I'm using windows10 and when I run Jest on VUEJS project for tests i've got this :
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { shallowMount } from '#vue/test-utils';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1086:14)
Itried a lot of soltions, but still not working Here is my jest.config.js file:
module.exports = {
moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
transform: {
"^.+\\.js$": "babel-jest",
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
},
moduleNameMapper: {
"^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
},
snapshotSerializers: [
"<rootDir>/node_modules/jest-serializer-vue"
],
testMatch: [
'<rootDir>/tests/**/*.spec.(js|jsx|ts|tsx)|<rootDir>/**/__tests__/*.(js|jsx|ts|tsx)'
],
transformIgnorePatterns: ['<rootDir>/node_modules/']
};

Related

How to properly import ES6+ React Native components with Jest ESM

Using Jest w/ESM for a React Native project, and can't figure out how to properly import modules that have ESM in them. Importing the react-native-phone-number-input module, I get Jest encountered an unexpected token:
/repo/node_modules/react-native-phone-number-input/lib/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import React, { PureComponent } from "react";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
So far the only way I have been able to get it running is mocking:
jest.unstable_mockModule('react-native-phone-number-input', () => ({
default: jest.fn(),
}));
Here is my Jest config (in package.json):
{
"haste": {
"defaultPlatform": "ios",
"platforms": [
"android",
"ios",
"native"
]
},
"resetMocks": true,
"testEnvironment": "node",
"testMatch": [
"**/src/**/*.(spec|test).[tj]s?(x)"
],
"preset": "ts-jest/presets/default-esm",
"transform": {
"^.+\\.js$": "babel-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!((jest-)?react-native|#?react-native(-community)?)/)"
],
"extensionsToTreatAsEsm": [
".ts",
".tsx"
],
"globals": {
"ts-jest": {
"useESM": true
}
},
"setupFiles": [
"<rootDir>/node_modules/react-native/jest/setup.js"
],
"setupFilesAfterEnv": [
"#testing-library/jest-native/extend-expect"
]
}

Coverage Report with Jest and Vue not working

I am unit testing my Vue project with Jest and I get the code coverage in the console, no problems there, however the HTML report is not working -
package.json:
...
"unit": "jest --config test/unit/jest.conf.js --coverage",
...
jest.conf.js:
const path = require('path')
module.exports = {
verbose: true,
testURL: "http://localhost/",
rootDir: path.resolve(__dirname, '../../'),
moduleFileExtensions: [
'js',
'json',
'vue'
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1'
},
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest'
},
testPathIgnorePatterns: [
'<rootDir>/test/e2e'
],
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
setupFiles: ['<rootDir>/test/unit/setup'],
mapCoverage: true,
coverageDirectory: '<rootDir>/test/unit/coverage',
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/main.js',
'!src/router/index.js',
'!src/plugins/vuetify.js',
'!**/node_modules/**'
]
}
What might be the cause of that? Thank you in advance.
It looks like your coverage report property might need to be adjusted. You should try including html in your coverageReporters, like this:
module.exports = {
...
coverageReporters: ['html']
...
}

ElementUI tests throw ReferenceError: _Message is not defined

Bug report on ElementUI
I am using On-demand loading of ElementUI components. I've followed the instructions correctly and it works just fine when running the app.
The problem arises when I try to test with Jest and Vue test utils. None of the components I am importing seem to be found, so I get this error when running my tests:
ReferenceError: _Message is not defined
I get the same error for any of the other components, that my test touches.
On the bug report I mentioned above, I am being suggested that my babel configuration is not being applied in my testing environment? Or its something about my Jest configuration. I've tried various things to fix this:
Doing a manual mocks
Spying on the component
Importing the whole ElementUI package inside my test
Updating Jest configuration
Nothing seems to work and I have no idea what is wrong...
bebel.config.js
module.exports = {
presets: [
'#vue/app',
],
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk',
},
],
],
};
jest.config.js
module.exports = {
// roots: ['<rootDir>/src/', '<rootDir>/tests/'],
moduleFileExtensions: [
'js',
'jsx',
'json',
'vue',
],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest',
},
transformIgnorePatterns: [
'/node_modules/(?!element-ui)',
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
'^.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
},
snapshotSerializers: [
'jest-serializer-vue',
],
testMatch: [
'**/tests/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)',
],
testURL: 'http://localhost/',
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
collectCoverage: true,
coverageReporters: ['lcov', 'text-summary'],
};
I have a couple of suggestions for you here:
change this in jest.config.js
module.exports = {
moduleFileExtensions: [
'js',
'jsx',
'json',
'vue',
],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.(js|jsx)?$': 'babel-jest'
},
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
'^.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
},
snapshotSerializers: [
'jest-serializer-vue',
],
testMatch: [
'**/tests/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)',
],
testURL: 'http://localhost/',
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
collectCoverage: true,
coverageReporters: ['lcov', 'text-summary'],
};
and this in babel.config.js
module.exports = {
presets: [
'#vue/app',
],
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk',
},
],
],
"env": { "test": { "plugins": ["transform-es2015-modules-commonjs", "dynamic-import-node"] } }
};
Also I believe #babel/plugin-transform-modules-commonjs is needed in yarn.
Let me know if this works.

Vue Jest test suite failed to run: SyntaxError: Unexpected identifier

I've set up my Jest, and it runs properly. But when I create a test for a file that contains a spreadoperator the test suite fails.
I'm using Vue configured from the CLI with Jest.
What I have tried
I've tried adding the babel-plugin-transform-object-rest-spread as a plugin to the babel.config.js but this had no result.
I also tried adding the #babel/plugin-proposal-object-rest-spread as a plugin to the babel.config.js but this also had no result.
babel.config.js:
module.exports = {
presets: ["#babel/preset-env", "#vue/app"]
};
package.json (jest part):
"jest": {
"collectCoverage": true,
"collectCoverageFrom": [
"**/*.{js,vue}",
"!**/node_modules/**"
],
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"moduleNameMapper": {
"^#/(.*)$": "<rootDir>/src/$1"
},
"transform": {
"^.+\\.js?$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
}
}
component.spec.js:
import { shallowMount } from '#vue/test-utils';
import Component from '#/views/xx/x/Component.vue';
import Vue from 'vue';
import BootstrapVue from 'bootstrap-vue';
Vue.use(BootstrapVue);
describe('About component', () => {
let wrapper;
beforeEach(() => {
wrapper = shallowMount(Component);
});
test('is a Vue instance', () => {
expect(wrapper.isVueInstance()).toBeTruthy();
});
});
Error:
FAIL src/__tests__/views/x/Component.spec.js
● Test suite failed to run
D:\projects\project\project-frontend\node_modules\#babel\runtime-corejs2\helpers\esm\objectSpread.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _Object$getOwnPropertyDescriptor from "../../core-js/object/get-own-property-descriptor";
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
at src/views/xx/x/Component.vue:670:49
at Object.<anonymous> (src/views/xx/x/Component.vue:810:3)
In package.json
make sure this pluging"babel-core" version up to ^7.0.0-0 that like under.
"devDependencies": {
"babel-core": "^7.0.0-0"
}
The final step for me was to provide correct env variables in jest config an explanation why it needs it may be found here.Also make sure babel packages installed
Sharing whole config
// jest
process.env.VUE_CLI_BABEL_TARGET_NODE = true;
process.env.VUE_CLI_BABEL_TRANSPILE_MODULES = true;
module.exports = {
verbose: true,
roots: ["<rootDir>/src/", "<rootDir>/spec/"],
moduleFileExtensions: ['js', 'vue','json'],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
},
transform: {
"^.+\\.js$": "babel-jest",
"^.+\\.vue$": "vue-jest",
},
snapshotSerializers: [
"jest-serializer-vue"
]
}
// in package json
"#babel/core": "^7.9.6",
"#babel/plugin-transform-runtime": "^7.9.6",
"#babel/preset-env": "^7.9.5",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "^25.4.0",

Vuejs + Jest : "SyntaxError: Unexpected token <"

I have a Vue file which imports a Vue file from node_modules. This file seems to not be recognize as a vue file when imported and doesn't use vue-jest.
I tried to use an htmlLoader, but doesn't work either.
Here is the error I get :
path/node_modules/vue-loading-spinner/src/components/Jumper.vue:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<template>
SyntaxError: Unexpected token <
Here is my jest.conf.js :
const path = require('path')
module.exports = {
rootDir: path.resolve(__dirname, '../../'),
moduleFileExtensions: [
'js',
'json',
'vue',
'html'
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
"\\.(css|scss)$": "<rootDir>/test/utils/styleTransform.js"
},
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.vue$': '<rootDir>/node_modules/vue-jest',
"^.+\\.html$": "<rootDir>/test/utils/htmlLoader.js"
},
testPathIgnorePatterns: [
"<rootDir>/node_modules/"
],
modulePaths: [
"<rootDir>"
],
setupFiles: ['<rootDir>/test/unit/setup'],
testMatch: [
'<rootDir>/(test/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
],
testURL: 'http://localhost'
}
Thanks for your help.