Vue Jest Invalid or unexpected token - vue.js

I'm new to Jest and Vue, but I'm getting an error in one of my tests.
The error is:
Test suite failed to run
/...../node_modules/element-ui/lib/theme-chalk/table-column.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){#charset "UTF-8";.el-checkbox,.el-checkbox__input{white-space:nowrap;display:inline-block;position:relative}.el-checkbox{color:#606266;font-weight:500;font-size:14px;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;margin-right:30px}.el-checkbox.is-bordered{padding:9px 20px 9px 10px;border-radius:4px;border:1px solid #DCDFE6;-webkit-box-sizing:border-box;box-sizing:border-box;line-height:normal;height:40px}.el-checkbox.is-bordered.is-checked{border-color:#409EFF}.el-checkbox.is-bordered.is-disabled{border-color:#EBEEF5;cursor:not-allowed}.el-checkbox.is-bordered+.el-checkbox.is-bordered{margin-left:10px}.el-checkbox.is-bordered.el-checkbox--medium{padding:7px 20px 7px 10px;border-radius:4px;height:36px}.el-checkbox.is-bordered.el-checkbox--medium .el-checkbox__l
SyntaxError: Invalid or unexpected token
Here's my package.json file:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.(vue)$": "vue-jest",
".*\\.(js)$": "babel-jest"
},
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"^#/(.*)$": "<rootDir>/src/$1"
},
"testPathIgnorePatterns": [
"<rootDir>/(build|docs|node_modules)/*"
],
"testEnvironment": "node"
},
"babel": {
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
]
},
I don't understand why node_modules isn't being excluded, but even if they aren't excluded why isn't the .css file being mocked?

I suspected the issue was jest was not reading my config from package.json.
To verify this I used the jest --showConfig. Indeed, it was different from package.json.
I then created a new config file, jest.json and I changed the test script in package.json to be "test": "jest --config jest.json"
This is the contents of my config:
{
"verbose": true,
"automock": false,
"globals": {
"_Table": {"name": "el-table"},
"_TableColumn": {"name": "el-table-column"}},
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.(vue)$": "vue-jest",
".*\\.(js)$": "babel-jest"
},
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"^#/(.*)$": "<rootDir>/src/$1"
},
"testPathIgnorePatterns": [
"<rootDir>/(build|docs|node_modules)/"
]
}
There are a few more issues, but this was the main one.

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"
]
}

Vue + jest debug

i'm trying to debug in vs code my vue project which uses jest for testing.
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',
'^.+\\.jsx?$': 'babel-jest'
},
transformIgnorePatterns: [
'/node_modules/',
'/node_modules/(?!#babel)'
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: [
'jest-serializer-vue'
],
testMatch: [
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],
testURL: 'http://localhost/',
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname'
]
}
launch.json :
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Unit Tests",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run-script",
"test:debug",
"${file}"
],
"port": 9229
}
]
}
I've tried almost every tutorial online like :
https://medium.com/#sarngru/debug-vuejs-jest-tests-in-vscode-63e2ed45e503
when tried to run debugging got :
node_modules\.bin\vue-cli-service:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
^^^^^^^
SyntaxError: missing ) after argument list
at new Script (vm.js:83:7)
at createScript (vm.js:267:10)
at Object.runInThisContext (vm.js:319:10)
at Module._compile (internal/modules/cjs/loader.js:684:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
at executeUserCode (internal/bootstrap/node.js:342:17)
Waiting for the debugger to disconnect...
tried npm install -g #vue/cli-service-global but it doesnt work as well.. plese help! thanks!
This works for me
launch.json :
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Jest",
"program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
"args": ["-i"],
"skipFiles": ["<node_internals>/**/*.js", "node_modules"]
}
]
}

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.

jest config hanging when getting coverage

I have a vue application that has got jest installed as the testing framework. The jest config is in the package.json file. It looks like:
"jest": {
"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"
},
"moduleNameMapper": {
"^#/(.*)$": "<rootDir>/src/$1"
},
"snapshotSerializers": [
"jest-serializer-vue"
],
"testMatch": [
"**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)",
"**/tests/unit/**/*.test.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
],
"testURL": "http://localhost",
"collectCoverage": true,
"collectCoverageFrom": [
"!**/node_modules/**",
"**/*.{js,vue}"
],
"coverageDirectory": "../coverage",
"coverageReporters": [
"html",
"text-summary"
]
}
These are i think the default setting when i installed the vue application using the vue cli.
I am experiencing issues after my tests run the terminal says Running coverage on untested files... and then it just hangs there forever.
If i remove the js bit from "**/*.{js,vue}" in the collectCoverageFrom so that it is "**/*.{vue}" then the problem doesn't occur and the coverage report completes.
Does anyone have experience of this problem? are there any config settings needed to prevent this issue?

Angular 6 with Saas Module not found: Error

I am new to angular and trying to setup it locally. I am facing an error and trying to fix from last 1 day.
Here is the error i am getting:
ERROR in multi ./scss/styles.scss ../node_modules/font-awesome/css/font-awesome.css ./scss/font-awesome.scss
Module not found: Error: Can't resolve 'D:\angular\my-app\scss\font-awesome.scss' in 'D:\miet\miet-app'
ERROR in multi ./scss/styles.scss ../node_modules/font-awesome/css/font-awesome.css ./scss/font-awesome.scss
Module not found: Error: Can't resolve 'D:\angular\my-app\scss\styles.scss' in 'D:\miet\miet-app'
ERROR in multi ./scss/styles.scss ../node_modules/font-awesome/css/font-awesome.css ./scss/font-awesome.scss
Module not found: Error: Can't resolve 'D:\angular\node_modules\font-awesome\css\font-awesome.css' in 'D:\angular\my-app
My folder structure is D:\miet\miet-app and inside this folder i have node_modules and src folders
Here is my angular.json file:
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"miet-app": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {
"#schematics/angular:component": {
"styleext": "scss"
}
},
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/miet-app",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"scss/styles.scss",
"../node_modules/font-awesome/css/font-awesome.css",
"../node_modules/font-awesome/scss/font-awesome.scss"
],
"stylePreprocessorOptions": {
"includePaths": [
"../node_modules/bootstrap/scss",
"scss"
]
},
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
}
},
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "miet-app:build"
},
"configurations": {
"production": {
"browserTarget": "miet-app:build:production"
}
}
},
"extract-i18n": {
"builder": "#angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "miet-app:build"
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.scss"
],
"scripts": [],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"miet-app-e2e": {
"root": "e2e/",
"projectType": "application",
"architect": {
"e2e": {
"builder": "#angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "miet-app:serve"
},
"configurations": {
"production": {
"devServerTarget": "miet-app:serve:production"
}
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "miet-app"
}
I have placed my font-awesome files inside src/scss/font-awesome and in node_module/font-awesome
Here is my app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { AngularFontAwesomeModule } from 'angular-font-awesome';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AngularFontAwesomeModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Can anyone help me where i am wrong.
Thanks
Try:
npm --depth 9999 update
npm rebuild node-sass
If doesn't work remove node_modules folder and repeat commands above.