Jest can't find several files in the __tests__ folder - vue.js

I want to use jest with vue.js framework. When I run yarn test:unit (eg. vue-cli-service test:unit) the only recognized file in the tests folder is the last, however I have several files.
I don't understand why. I tried to add the path of the folder tests, of the other files, without success
Could you help me please ?
I used vue add unit-jest in an existing project.
Here the structure of my project :
> __tests__
example.test.js
example1.test.js
example2.test.js
example3.test.js
example4.test.js
> src
// jest.config.js
module.exports = {
verbose: true,
preset: '#vue/cli-plugin-unit-jest',
testMatch: [
'<rootDir>/**/*.(test).{js,jsx,ts,tsx}',
'<rootDir>/**/?(*.)(spec|test).{js,jsx,ts,tsx}',
],
transformIgnorePatterns: ['/node_modules/(?!vuetify|vue-select)'],
setupFiles: ['./utils/setup.js'],
//.eslintrc
"env": {
"jest": true
}
// package.json
"scripts": {
"test:unit": "vue-cli-service test:unit --watch=all --coverage",
}
versions :
"#vue/test-utils": "^1.1.3",
"#vue/vue2-jest": "^27.0.0-alpha.2",
"babel-jest": "^27.0.6",
"jest": "^27.0.5",
"#vue/cli-plugin-unit-jest": "~5.0.0",
output :
PASS __tests__/example4.test.js (6.415 s)
App.vue
√ should return true (12 ms)
...
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 7.217 s
Ran all test suites.
Done in 10.71s.

Not sure but can you try to replace the testMatch on config.jest.js to something like this?
testMatch: [
'<rootDir>/**/*.test.js',
],

Related

mocha cannot compile ES6, even with correct options

I'd like to run mocha on a test directory. My tests are written in ES6, therefore I added babel to compile them. Although, even after adding all required modules, and adding a mocha.opts file inside of my test directory, I still get this error
{ import sinon from 'sinon';
^^^^^
SyntaxError: Unexpected identifier
mocha.opts :
--slow 2000
--timeout 15000
--require #babel/register
--recursive test/src
package.json command:
"test": "mocha"
modules :
"#babel/cli": "^7.2.3",
"#babel/core": "^7.3.4",
"#babel/plugin-transform-runtime": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"#babel/register": "^7.4.0",
"#babel/runtime": "^7.3.4",
If anything, I also added a .babelrc file in my test directory
{
"presets": ["#babel/preset-env"],
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"helpers": true,
"regenerator": true
}
]
]
}
Did I miss something ?
I had exactly the same issue, and your question gave me the answer. My .babelrc file looks like this:
{
"presets": ["#babel/preset-env"],
"comments": false,
"env": {
"test": {
"presets": [
"#babel/preset-env"
]
},
// ...Other environment settings...
},
"plugins": ["#babel/plugin-transform-runtime"]
}
Removing the helpers and regenerator parameter worked for me.

Learning JEST w Vue.js : error on forst example test

I am trying to learn JEST for testing my Vue apps..
I started discovering it by running a standard vue-cli (3) example, with full config ( babel, lint, vuex, vue-router, unit and e2e tests)
vue create cli-test
generated package.json
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"#vue/prettier"
],
"rules": {},
"parserOptions": {
"parser": "babel-eslint"
}
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
],
"jest": {
"moduleFileExtensions": [
"js",
"jsx",
"json",
"vue"
],
"transform": {
"^.+\\.vue$": "vue-jest",
".+\\.(css|styl|less|sass|scss|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)"
],
"testURL": "http://localhost/"
}
I run lint wo any error
yarn lint
then I run test:unit, with an error on the import statement in the only generated spec file tests/unit/HelloWorld.spec.js
yarn run test:unit
yarn run v1.9.2
$ vue-cli-service test:unit
FAIL tests/unit/HelloWorld.spec.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/yves/Developments/WIP/TESTS/cli-test/tests/unit/HelloWorld.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import "core-js/modules/es6.array.iterator";
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 5.532s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
why this generated test does not pass ? should not it be ielf checked before being autogenerated ? too bad start for learning ... or being optimist, this error is raised to challenge immediatly the newbie ...
need to upgrade babel-jest
yarn upgrade babel-jest#23.4.0"
then test:uniy passed
yarn run test:unit
yarn run v1.9.2
$ vue-cli-service test:unit
PASS tests/unit/HelloWorld.spec.js
HelloWorld.vue
✓ renders props.msg when passed (30ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 7.349s
Ran all test suites.

How to build everything into a dist with folder structure by webpack?

I am a java developer for years and just new to the js world. This question sounds stupid but I don't know what's the proper/best way to build a dist for reactjs app for deploying to production(nginx/apache).
From my understanding, the dist just like simple web app and should looks like
contains:
index.html
client.js (bundled js after compiled)
static files, e.g.
images, css, js libraries, etc
I follow the guide on:
https://github.com/learncodeacademy/react-js-tutorials/tree/master/1-basic-react
and have a simple web app(maybe this is not called web app) running by:
npm run dev
it uses webpack to bundles the client.js.min and deploy to a embedded web server by node(maybe i am wrong).
Question:
How to build all the things by a command, say "npm run build" and it should built everything in a folder called "dist". So I can deploy it to web server root by copying every in dist to the web root.
package.json
{
"name": "react-tutorials",
"version": "0.0.0",
"description": "",
"main": "webpack.config.js",
"dependencies": {
"babel-core": "^6.17.0",
"babel-loader": "^6.2.0",
"babel-plugin-add-module-exports": "^0.1.2",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.3.13",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
"react": "^0.14.6",
"react-dom": "^0.14.6",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.1"
},
"devDependencies": {},
"scripts": {
"dev": "webpack-dev-server --content-base src --inline --hot",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
webpack.config.js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : false,
entry: "./js/client.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
}
]
},
output: {
path: __dirname + "/src/",
filename: "client.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
In your scripts dictionary of package.json add the following
"build" : "NODE_ENV='production' && node_modules/.bin/webpack -p"
This will tell webpack to read the config file and build it in production mode i.e minify etc etc. The -p flag does it. The node env is to ensure that production build are used for react and other libraries and to set an env variable of production for NODE_Env
To run type. npm run build

Jest - Unknow "preset" - "jest-react-native"

I'm using the following package.json (according to http://facebook.github.io/jest/docs/tutorial-react-native.html#content):
{
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest",
},
"dependencies": {
"react": "^15.3.1",
"react-native": "0.31.0",
},
"devDependencies": {
"babel-jest": "^14.1.0",
"babel-preset-react-native": "^1.9.0",
"jest": "^14.1.0",
"jest-cli": "^13.1.0",
"jest-react-native": "^14.1.3",
"react-test-renderer": "^15.3.1"
},
"jest": {
"globals": {
"__DEV__": true,
"__RCTProfileIsProfiling": false
},
"preset": "jest-react-native"
}
}
But I get the error:
Error: Unknown config option "preset" with value "jest-react-native". This is either a typing error or another user mistake and fixing it will remove this message.
Using Jest CLI v13.2.3, jasmine2, babel-jest
FAIL __tests__/AuthorRequest-test.js (0s)
● Runtime Error
- Error: Cannot find module 'throwOnWrongReactAPI' from 'react-native.js'
at Resolver.resolveModule (node_modules/jest-cli/node_modules/jest-resolve/build/index.js:197:17)
at eval (node_modules/react-native/Libraries/react-native/react-native.js:180:26)
at Object.<anonymous> (node_modules/react-native/Libraries/react-native/react-native.js:189:4)
1 test suite failed, 0 tests passed (0 total in 1 test suite, run time 2.238s)
npm ERR! Test failed. See above for more details.
my .babelrc file contains:
{
"presets": ["react-native"]
}
I have a feeling that you are using a wrong version of Jest. You have:
"jest": "^14.1.0",
"jest-cli": "^13.1.0"
But it seems you have 13.2.3installed using npm -g:
Using Jest CLI v13.2.3, jasmine2, babel-jest
First of all, I think you can remove jest-cli and just use jest 14.1.0.
Then you can update your test script like:
"scripts": {
"test": "./node_modules/jest/bin/jest.js"
}
In this way, you make sure you run the local Jest copy of your project, so it should say now:
Using Jest CLI v14.1.0, jasmine2, babel-jest
Doing that and following the official docs you posted, it should be everything you need (Can't say for sure since you did not post the test code).

How to make test coverage show all vue files in Vue-cli 3 using jest

I am having difficulty trying to set up Vue CLI 3 with Jest to show test coverage. I have done everything possible to make it work, but it is still showing no coverage:
Ran all test suites.
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 0 | 0 | 0 | 0 | |
----------|----------|----------|----------|----------|-------------------|
=============================== Coverage summary ===============================
Statements : Unknown% ( 0/0 )
Branches : Unknown% ( 0/0 )
Functions : Unknown% ( 0/0 )
Lines : Unknown% ( 0/0 )
Below is an excerpt of my configuration:
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'
},
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: [
'jest-serializer-vue'
],
testMatch: [
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],
transformIgnorePatterns: ['<rootDir>/node_modules/'],
testURL: 'http://localhost/'
}
package.json:
....
"scripts": {
"test:unit": "nyc vue-cli-service test:unit"
},
"nyc": {
"check-coverage": true,
"per-file": true,
"lines": 90,
"statements": 90,
"functions": 90,
"branches": 90,
"include": [
"src/**/*.{js,vue}"
],
"exclude": [
"src/*.js"
],
"reporter": [
"lcov",
"text",
"text-summary"
],
"extension": [
".js",
".vue"
],
"verbose": true,
"cache": true,
"all": true
}
How do I properly configure Vue CLI 3 and Jest to show test coverage?
Jest has its own coverage facilities, so remove nyc from package.json:
"scripts": {
// "test:unit": "nyc vue-cli-service test:unit" // DELETE
"test:unit": "vue-cli-service test:unit"
},
// "nyc": {...} // DELETE
To enable Jest's coverage, set collectCoverage and collectCoverageFrom in jest.config.js (per the vue-test-utils docs):
collectCoverage: true,
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/main.js', // No need to cover bootstrap file
],
Running yarn test:unit should yield console output like this:
GitHub demo
Also note that the Jest console output only lists files that contain executable JavaScript (methods for Vue SFCs). If you're working off the default Vue CLI generated template, HelloWorld.vue contains no methods, so it won't be listed. In the screenshot above, I've added an unused method to HelloWorld.vue to demonstrate Jest's uncovered lines report.
While #tony19's answer is perfectly valid, you don't necessarily need to add anything in your custom jest configuration. For a project built with the Vue CLI service, just adding the following script in the package.json worked fine, and the coverage is showing up for Vue components:
"test:coverage": "vue-cli-service test:unit --coverage",
There are additional options you can add, such as changing the reporter(s), and having a distinct Jest configuration just for this script. To get the full list of options, you can run the following command in your terminal:
npx vue-cli-service test:unit help
And, among these options, you'll find collectCoverage and collectCoverageFrom which can help you keep everything in the script, rather than having a custom config file.
If you don't use Vue CLI plugin #vue/cli-plugin-unit-jest, you can still generate test coverage report for Vue components. You can have Jest configured similar to the following way:
jest.config.js
module.exports = {
moduleFileExtensions: ['js', 'json', 'vue'],
transform: {
'^.+\\.js$': 'babel-jest',
'^.+\\.vue$': 'vue-jest'
},
collectCoverage: true,
collectCoverageFrom: ['src/**/*.{js,vue}', '!src/main.js']
}
Then you can generate the coverage report by simply running npx jest.
The coverage reports will look like below:
(1) Terminal
(2) HTML