I have react component to test, I import its CSS using webpack as the following.
import styles from '../../node_modules/openlayers/css/ol.css' // eslint-disable-line no-unused-vars
After running jest I get error:
C:\Users\...\node_modules\openlayers\css\ol.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.ol-box {
^
SyntaxError: Unexpected token .
How to exclude css files from jest test suites?
Or better yet, add
yarn add --dev identity-obj-proxy
And add the following to jest.config.json
{
"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|scss|sass)$": "identity-obj-proxy"
},
}
}
You can create your own mock in jest to prevent processing of css files.
// __mocks__/styleMock.js
module.exports = {};
Then in your package.json you can map any css files to the styleMock.js file under moduleNameMapper option:
"jest": {
...
"moduleNameMapper": {
...
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
},
..
},
See https://facebook.github.io/jest/docs/en/webpack.html#handling-static-assets
for more info.
Related
Edit: This post got out of hand with edits, please follow this link to a new Stackoverflow post which is clearer:
SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial
There are thousands of posts and threads about this issue and I still can't fix my problem.
I followed the "Getting started" portions of Jest AND Mocha and get the same error both times:
SyntaxError: Cannot use import statement outside a module but their provided link doesn't help at all.
Theres a new edit at the bottom with steps for a clean new project with jest for you to follow along which results in an error.
"vue-jest": "^3.0.7",
"vue": "^2.6.12",
"#vue/test-utils": "^1.2.2"
package.json
"mocha": "mocha 'tests/Frontend/**/*.test.js'"
example.test.js:
import { mount } from "#vue/test-utils"
import Dashboard from "../../resources/js/views/Dashboard";
import * as assert from "assert";
describe('test example', () => {
it('should work', () => {
assert.equal([1, 2, 3].indexOf(4), -1); // doesn't matter what I do here
})
})
What I've tried:
Using the --require #babel/register flag with mocha
Setting "transformIgnorePatterns": [] and thus allowing all node_modules to be considered
Adding a .babelrc file with the following content: This resulted in following error on building the app though:
Error: Multiple configuration files found. Please remove one:
- package.json
- C:\Users\f.marchi\workspace\projects\sanctum-test\.babelrc
{
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Can someone confirm, that those docs are missing some very important steps? I really don't know what I'm doing wrong, I'm just following the tutorials.
Edit: jest.config.js:
module.exports = {
clearMocks: true,
collectCoverage: true,
coverageDirectory: "coverage",
moduleFileExtensions: [
"js",
"json",
"vue"
],
transform: {
".*\\.(vue)$": "vue-jest"
},
transformIgnorePatterns: []
};
Edit:
I just tried again, you can follow along if you want:
vue create jest-test
npm install --save-dev jest #vue/test-utils vue-jest
Added jest config to package.json:
{
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.(vue)$": "vue-jest"
}
}
}
npm install --save-dev babel-jest #babel/core #babel/preset-env babel-core#^7.0.0-bridge.0
Adjusted jest config to:
{
"jest": {
"transform": {
// process `*.js` files with `babel-jest`
".*\\.(js)$": "babel-jest" //<-- changed this
}
}
}
Adjusted babel config to:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset',
'#babel/preset-env' //<-- added this
]
};
You should use vue-cli API.
In your package.json add to scripts this:
"test:unit": "vue-cli-service test:unit"
You have vue-cli and test-utils installed so it should now work.
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)
vue create jest-test
1.1. npm install
npm install --save-dev jest #vue/test-utils vue-jest
Added jest config to package.json:
{
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.(vue)$": "vue-jest"
}
}
}
npm install --save-dev babel-jest #babel/core #babel/preset-env babel-core#^7.0.0-bridge.0
Adjusted jest config to:
{
"jest": {
"transform": {
// process `*.js` files with `babel-jest`
".*\\.(js)$": "babel-jest" //<-- changed this
}
}
}
Adjusted babel config to:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset',
'#babel/preset-env' //<-- added this
]
};
Created example.test.js in a tests directory under the project root (jest-test/tests)
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')
})
Added the following to the package.json scripts:
"jest": "jest"
npm run jest
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
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'
}
I want to apply a jest test to react component and I get an error that says:
Jest encountered an unexpected token
When I try to:
import moment from 'moment';
import './style.css'; //<----here
I try to mock css files and image objects and change the configuration:
// package.json
{
"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"
}
}
}
My styleMock.js is:
module.exports = {};
My fileMock.js is:
module.exports = 'test-file-stub';
But I still get the error:
Jest encountered an unexpected token
and the error is in the same place as it was previously.
My jest is the latest version "24.8.0".
Anyone knows why?
i use this lib for that identity-obj-proxy
npm install identity-obj-proxy
change this line:
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
to this:
"\\.(css|less)$": "identity-obj-proxy"
I'm trying to create a simple web app with material-components-vue and vue-cli with webpack, however, I found out that I cannot import stylesheets from node_modules without a preceding ~.
I have tried several webpack/vue-cli configs, and ended up with a config in vue.config.js passing loader options.
My vue.config.js looks like this:
module.exports = {
css: {
loaderOptions: {
sass: {
includePaths: [
'./node_modules', //here I include node_modules
]
},
}
}
}
So I expect to be able to import stuff like so:
#import 'normalize/normalize'
(assuming I have a directory called normalize in my node_modules which contains a file normalize.scss)
However, webpack throws an error, saying it cannot find the module.
But, this does work:
#import '~normalize/normalize'
This wouldn't be a problem if all #imports were written by me, but because I use a third-party module which has #imports inside them, webpack fails to compile.
EDIT 1:
As #Styx asked to
Share more configs, please
and
show the output of vue inspect --rule scss, and the whole file with this problematic import
Here it is:
My problematic file is pretty empty:
<template>
<div id="app">
<m-button>Hello</m-button>
</div>
</template>
<script>
import Vue from 'vue'
import Button from 'material-components-vue/dist/button'
Vue.use(Button)
export default {
name: 'App',
components: {
}
</script>
<style lang="scss">
#import "~material-components-vue/dist/button/styles"; //this works
#import "material-components-vue/dist/button/styles"; //but this does not
</style>
My output from vue inspect --rule scss is located here
All other configs are as generated by vue init webpack <name>
EDIT 2: Exact steps to reproduce this issue:
Initialize a vue-webpack app:
vue init webpack .
Vue build: Runtime + Compiler (Default)
Vue-router: no
Package manager: npm
Then, install sass-loader
npm i -D sass-loader node-sass
Create a file vue.config.js and populate it with the following:
module.exports = {
css: {
loaderOptions: {
sass: {
includePaths: [
'./node_modules', //here I include node_modules
]
},
}
}
}
After that, install a module containing scss/sass
(E.g. for material-components-web, npm i material-components-web)
Then, create an import to a stylesheet located in node_modules, like so:
#import '#material/button/mdc-button'; //mdc-button comes with material-components-web
Finally, start the dev server:
npm run dev
It will throw the following error:
ERROR Failed to compile with 1 errors 11:36:35 AM
error in ./src/App.vue
Module build failed:
#import '#material/button/mdc-button';
^
File to import not found or unreadable: #material/button/mdc-button.
in /home/maxim/projects/holiday.js/stackoverflow/src/App.vue (line 18, column 1)
# ./node_modules/vue-style-loader!./node_modules/css-loader?{"sourceMap":true}!./node_modules/vue-loader/lib/style-compil
er?{"vue":true,"id":"data-v-7ba5bd90","scoped":false,"hasInlineConfig":false}!./node_modules/sass-loader/lib/loader.js?{"s
ourceMap":true}!./node_modules/vue-loader/lib/selector.js?type=styles&index=0!./src/App.vue 4:14-359 13:3-17:5 14:22-367
# ./src/App.vue
# ./src/main.js
# multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js
By the way, in the first example I wanted to import material-components-vue/dist/foo/styles, but here I import #material/foo.
In this configuration your vue.config.js is ignored. This file is used by #vue/cli-service, but you're using webpack-dev-server instead. Thus, your sass-loader doesn't receive this includePaths option.
You can either use modern vue create <app-name> command, or if you want to modify existing project:
Open build/utils.js file.
Find return ... in exports.cssLoaders function:
return {
...
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
...
}
Modify it like this:
const includePaths = [path.resolve(__dirname, '..', 'node_modules')];
return {
...
sass: generateLoaders('sass', { indentedSyntax: true, includePaths }),
scss: generateLoaders('sass', { includePaths }),
...
}
Remove unused vue.config.js file.
I have already integrated Detox to my react native project (using yarn workspaces) and it works ok. But when I want to use import syntax the tests fail.
This is the error:
import { linkBarTest } from './helpers';
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (../node_modules/jest-runtime/build/script_transformer.js:403:17)
I didn't have this issue with a non-monorepo setup.
My config.json file:
{
"setupTestFrameworkScriptFile": "./init.js",
"testEnvironment": "node"
}
My babel.config.js file:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: ['jsx-control-statements'],
}