Jest test coverage for VueJS application with Nuxt - vue.js

I have VueJS application written with NuxtJS. This setup causes that I have many files index.vue in different directories.
When I run the testing suite with commend jest --no-cache --watch --coverage only 1 file index.vue has being picked up by coverage results.
my configuration of jest in package.json is:
"jest": {
"transform": {
"^.+.vue$": "vue-jest",
"^.+.js$": "babel-jest"
},
"collectCoverage": true,
"collectCoverageFrom": [
"**/*.{js,vue}",
"!**/node_modules/**"
],
"coverageReporters": [
"text"
],
"setupTestFrameworkScriptFile": "jest-extended"
}
and results show only coverage for 1 index.vue file (even I have multiple of them as well other .vue files).
What configuration option I need to add to run coverage for all .vue files?

At a first sight, I would expect to see Jest's moduleFileExtensions config option in place like:
"jest": {
"moduleFileExtensions": ["js", "json", "jsx", "node", "vue"],
// The rest of your config...
}
The option tells Jest which file extensions are used by the modules of your application.

Related

Jest unexpected token - Typescript import

I am getting the following error when I run jest. It looks like the cause is Typescript-related but I have some typescript handling in the package.json, so I'm not sure why it wouldn't be handled.
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.
...
Details:
/Users/ryancocuzzo/ex/test/example/mobile-app/node_modules/react-native-fs/FS.common.js:30
var normalizeFilePath = (path: string) => (path.startsWith('file://') ? path.slice(7) : path);
^
SyntaxError: Unexpected token ':'
> 1 | import RNFS from "react-native-fs";
The library in question is react-native-fs.
package.json:
"jest": {
"preset": "react-native",
"setupFiles": [
"./setupTests.js",
"./node_modules/react-native-gesture-handler/jestSetup.js"
],
"transform": {
"^.+\\.ts?$": "ts-jest",
"^.+\\.tsx?$": "ts-jest",
"^.+\\.js$": "./node_modules/react-native/jest/preprocessor.js"
},
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)?$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"moduleNameMapper": {
"^.+\\.(css|less|scss)$": "identity-obj-proxy"
}
}
Info:
react: 17.0.1
react-native: 0.64.1
react-native-fs: 2.18.0
ts-jest: 27.1.3
jest: 26.6.3
babel-jest: 26.6.3
Did you take a look at here ? Also related issue.
A workaround could be adding react-native-fs to the transformIgnorePatterns.
Use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories.
You also need to set the test environment for your react-native tests. so that it mimics the environment of a React Native app as it doesn't load any DOM or browser APIs, which would greatly improves Jest's startup time.
{
//...
"testEnvironment": "node",
"transform": {
"^.+\\.ts?$": "ts-jest",
"^.+\\.tsx?$": "ts-jest",
// use <rootDir> absolute path here
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
}

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.

Unexpected token 'import' error while running Jest tests?

I realize this question has been asked several times but all of the solutions I've come across don't seem to work for me. I'm running into the following error while trying to run Jest tests for a Vue app.
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://facebook.github.io/jest/docs/en/configuration.html
Details:
/node_modules/vue-awesome/icons/expand.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue'
^^^^^^
SyntaxError: Unexpected token import
> 17 | import 'vue-awesome/icons/expand'
.babelrc:
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}]
],
"env": {
"test": {
"presets": [
["env", { "targets": { "node": "current" }}]
]
}
}
}
jest config in package.json:
"jest": {
"moduleFileExtensions": [
"js",
"vue"
],
"moduleNameMapper": {
"^#/(.*)$": "<rootDir>/src/$1"
},
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
},
"snapshotSerializers": [
"<rootDir>/node_modules/jest-serializer-vue"
],
"moduleDirectories": [
"node_modules",
"src"
]
}
It looks like the initial import in the script for the Vue component being mounted for the test is working but the import within the module itself (import Icon from '../components/Icon.vue) is not recognized.
boiler plate repo to re-creates the issue: github.com/DonaldPeat/stackoverflow-jest-question
How can I resolve this?
You just need to make sure that vue-awesome will be transformed by jest, so add
following to your jest config:
transformIgnorePatterns: ["/node_modules/(?!vue-awesome)"],
which means: "Ignore everything in node_modules except for vue-awesome.
Also here is exhausive list of other issues that might cause this error: https://github.com/facebook/jest/issues/2081
If you are encountering this problem after updating to a newer Jest version, try clearing Jest's internal cache:
jest --clearCache
Adding this in the package.json works for me (replace <package_name> with causing package name)
"jest": {
"transformIgnorePatterns": ["node_modules/(?!<package_name>)/"]
}
We had the same issue with another library. The root cause was that we had a circular dependency in code. But the error text did not refer to it at all. just like in this post: "Jest encountered an unexpected token..."
In my case I needed testEnvironment: "node" in jest.config.js file. The error came out when I started tests against Vue Router.
// jest.config.js
module.exports = {
preset: "#vue/cli-plugin-unit-jest/presets/typescript",
transform: {
"^.+\\.vue$": "vue-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",
},
testEnvironment: "node", // It fixes my issue
};

Including bootstrap css in Aurelia

I am new to Aurelia and falling at the first hurdle.
I have created a new project using the aurelia cli and have selected to use less.
This works fine until I try to use bootstrap. I have installed bootstrap with npm which appears in node_modules/bootstrap/
This has the directory structure
dist fonts grunt Gruntfile.js js less LICENSE package.json README.md
There are css files in the dist directory.
In my template I do
The error I get is
Unhandled rejection Error: Failed loading required CSS file: bootstrap/css/bootstrap.css
How do I tell Aurelia where the bootstrap css files are and how to use them ?
Thanks
I found out one simple thing. Every time you modify aurelia.json file, you need to terminate au run --watch task, a start it again, and it will just work.
I did not find this in documentation.
Hope this helps.
There is solution for bootstrap downloaded from npm:
app.html:
<require from="bootstrap/css/bootstrap.css"></require>
package.json you have to add:
"overrides": {
"npm:jquery#^3.0.0": {
"format": "amd"
}
}
aurelia.json (aurelia_project folder) you have to add at the end of "app-bundle.js" bundle:
"dependencies": [
"jquery",
{
"name": "bootstrap",
"path": "../node_modules/bootstrap/dist",
"main": "js/bootstrap.min",
"deps": ["jquery"],
"exports": "$",
"resources": [
"css/bootstrap.css"
]
}
]
It should look like this:
"bundles": [
{
"name": "app-bundle.js",
"source": [
"[**/*.js]",
"**/*.{css,html}"
],
"dependencies": [
"jquery",
{
"name": "bootstrap",
"path": "../node_modules/bootstrap/dist",
"main": "js/bootstrap.min",
"deps": ["jquery"],
"exports": "$",
"resources": [
"css/bootstrap.css"
]
}
]
},
It works for me.
We are still working on the CLI's ability to import libraries into a project and configure them correctly for bundling. Remember, it is an alpha. We will have major improvements coming for this in the future. In the mean time, remember that you can always use traditional techniques for including libraries if you aren't sure what to do. So, I would just include the style tag in your html page and a script tag as well, just pointing at the location for the files in your packages folder.
This is a major use case for us, we just haven't worked out all the library import capabilities yet. We will address this soon.
Using Aurelia CLI
First, install the following in your project:
au install jquery#2
au install bootstrap
Second, in aurelia.json add this line in bundles:vendor-bundle.js
"jquery",
{
"name": "bootstrap",
"path": "../node_modules/bootstrap/dist",
"main": "js/bootstrap.min",
"deps": [
"jquery"
],
"resources": [
"css/bootstrap.css"
],
"exports": "$"
}
Then Add the following fonts after dependecies
"copyFiles": {
"node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2": "bootstrap/fonts",
"node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.woff": "bootstrap/fonts",
"node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf": "bootstrap/fonts"
}
Third, After setting import/install. Now you can reference it inside your app.html
<require from="bootstrap/css/bootstrap.css"></require>
Or simply add it as a globalResources inside main.ts
aurelia.use
.standardConfiguration()
.feature('resources')
.globalResources('bootstrap/css/bootstrap.css');
For more information on au install/import check it here or adding library in bundles.
I found that I had to change the boostrap css path in app.html to the one expected for Bootstrap 4, per a comment on Aurelia Discourse:
from this:
<require from="bootstrap/css/bootstrap.css"></require>
to this:
<require from="bootstrap/dist/css/bootstrap.css"></require>
If you are here in July 2019, the answer by #davidjmcclelland is what worked for me. After installing bootstrap, simple include require from=bootstrap/dist/css/bootstrap.css> in your app.html. No configurations required.

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