Running Jest tests in Vue.js - vue.js

Basically, the component isn't getting compiled, so I get an Unexpected token < error when it runs into <template>
I've run the following commands:
$ npm install --save-dev jest
$ npm install --save-dev vue-jest
$ npm install --save-dev vue-test-utils
and I've out the following in package.json:
"scripts": {
"dev": "node build/dev-server.js",
"build": "node build/build.js",
"test": "jest"
},
...
"jest": {
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/vue"
],
"moduleFileExtensions": [
"js",
"vue"
],
"scriptPreprocessor": "index.js"
}
I created a __test__ folder in the root directory with a simple test:
const Vue = require("vue");
const VueTestUtils = require("vue-test-utils");
Vue.config.debug = true;
Vue.config.async = false;
Vue.use(VueTestUtils.install);
import Hello from '../src/components/Hello.vue'
const Constructor = Vue.extend(Hello)
const vm = new Constructor().$mount()
describe('initial test', () => {
it('should be 1', () => {
expect(1).toBe(1)
})
})
I recently got this error as well, and not quite sure how to configure Vue.js so it will run using the compiler-included build:
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
Been looking around for a while, so any help would be appreciated

You need to use a Jest transform to transform Jest Vue files. A Jest transformer is a synchronous function, that takes the file and path as input and outputs transpiled code.
I maintain a npm package that does it for you - vue-jest.
npm install --save-dev vue-jest
You need to add a jest section to your package.json (or in a seperate file with --config). Your config should look something like this:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
"^.+\\.js$": "babel-jest",
".*\\.(vue)$": "vue-jest"
}
}
This tells jest to use jest-vue as a transform for files with a .vue extension.
You can see a working repo using Vue Test Utils here - https://github.com/eddyerburgh/vue-test-utils-jest-example

Related

Fullcalendar custom css with Vue3 and postcss

I am using fullcalendar with vue3. I want to change change colors for button and text in fullcalendar.
vue version
"vue": "^3.2.26",
I am getting error
Syntax Error: Error: PostCSS plugin postcss-custom-properties requires
PostCSS 8.
I am following steps mentioned in fullcalendar documentation.
fullcalendar-vars.css
:root {
--fc-border-color: green;
--fc-button-text-color: #ff0000;
}
I have installed following packages
"postcss": "^8.4.7",
"postcss-calc": "^8.2.4",
"postcss-custom-properties": "^12.1.4",
"postcss-loader": "^6.2.1",
Added postcss.config.js at root
module.exports = {
plugins: [
require('postcss-custom-properties')({
preserve: false, // completely reduce all css vars
importFrom: [
'client/fullcalendar-vars.css' // look here for the new values
]
}),
require('postcss-calc')
]
}
And my vue.config.js as follow
const path = require("path");
module.exports = {
pages: {
index: {
entry: "./client/main.js",
},
},
outputDir: path.resolve(__dirname, "./client/dist"),
};
Also I would like to know, Do I need make any changes in vue.config.js?
PostCSS error
Vue CLI scaffolded projects already include PostCSS (including postcss, postcss-calc, and postcss-loader), so you don't need to install it in your project. The only dependency needed here is postcss-custom-properties.
To resolve the PostCSS error, you should uninstall the PostCSS dependencies that you had mistakenly added:
npm uninstall --save-dev postcss postcss-calc postcss-loader
Starting from scratch
To setup custom colors for FullCalendar in a Vue CLI scaffolded project:
Install postcss-custom-properties with:
npm install --save-dev postcss-custom-properties
Create postcss.config.js with the following PostCSS configuration:
// <projectRoot>/postcss.config.js
module.exports = {
plugins: [
require("postcss-custom-properties")({
preserve: false,
importFrom: [
"client/fullcalendar-vars.css",
],
}),
require("postcss-calc"),
],
}
Create fullcalendar-vars.css with the following CSS:
/* <projectRoot>/client/fullcalendar-vars.css */
:root {
--fc-border-color: green;
--fc-button-text-color: #ff0000;
}
Note: Changes to this file are not hot-reloaded, so the dev server must be restarted to reflect any updates.
Start the Vue CLI dev server with:
npm run serve
demo

Babel - VueJS | Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions. In

i tried to install preset-env for using environment variables. After that, my VueJS project got an error, i tried npm r #babel/preset-env, i tried npm i --save #babel-core but nothing changed. Any thoughts?
{
"presets": [
["env", { "modules": false }],
"stage-3",
],
"plugins": [["transform-runtime", { "polyfill": false, "regenerator": true }]]
}
Problem solved with using Babel version from vue.js webpack template repository.
npm r babel-core
add "babel-core": "^6.22.1" to package.json
npm i

run webpack as a postinstall npm script

I'm updating a private node_module that we install in projects via bitbucket. The package has some overrides that get bundled up via webpack and that bundle is used directly (i.e. outside of the build tools used for the project I'm installing the module for).
I would like to fire the module's build command as a postinstall script so that when we install or update the module in the main project the bundle is rebuilt.
In the module's package.json I have this:
"scripts": {
"build": "webpack",
"dev": "webpack --watch",
"serve": "webpack-dev-server",
"postinstall": "npm run build"
},
and I have the following webpack.config.js file:
const path = require("path")
module.exports = {
mode: "development",
watch: false,
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
},
devServer: {
contentBase: "dist",
},
module: {
rules: [
{
test: /\.js/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
},
],
},
}
And I've confirmed that firing npm run build works just fine in the modules codebase, but when I go to update the module in the main codebase I get errors:
Webpack is blowing up on the option chaining which I thought would be handled by the babel loader in the module's webpack config.
I double checked my module's package.json file and it definitely has babel's presets in the regular dependencies and not the dev dependencies (i.e. it gets installed as part of the module install).
Am I doing something wrong here? It seems like if the same build process works
Make sure your exports in the package.json points to the sources in the dist:
"exports": {
".": "./dist/bundle.js"
},
https://nodejs.org/api/packages.html#package-entry-points

GULP: gulp is not defined

As shown in the screen shot below I am not able to run gulp to concat the JavaScript files. Its saying that gulp is not defined.
I have tried the following commands:
npm install -g gulp
npm install gulp
npm install gulp --save-dev
I have also set the environment variables as following:
C:\Users\<user>\AppData\Roaming\npm;C:\Python27;C:\Users\<user>\AppData\Roaming\npm\node_modules;C:\Users\<user>\AppData\Roaming\npm\node_modules\gulp;
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
//script paths
var jsFiles = 'scripts/*.js',
jsDest = 'dist/scripts';
gulp.task('scripts', function() {
return gulp.src(jsFiles)
.pipe(concat('scripts.js'))
.pipe(gulp.dest(jsDest));
});
you just need to install and require gulp locally, you probably only installed it globally
At the command line
cd <project-root> && npm install --save-dev gulp
In your gulpfile.js
var gulp = require('gulp');
this is a different dependency than the command line dependency (that you installed globally). More specifically, it is the same NPM package, but the command line program will execute code usually from a different entry point in the NPM package then what require('X') will return.
If we go to the package.json file in the Gulp project on Github, it will tell the whole story:
{
"name": "gulp",
"description": "The streaming build system",
"version": "3.9.1",
"homepage": "http://gulpjs.com",
"repository": "gulpjs/gulp",
"author": "Fractal <contact#wearefractal.com> (http://wearefractal.com/)",
"tags": [ ],
"files": [
// ...
],
"bin": {
"gulp": "./bin/gulp.js"
},
"man": "gulp.1",
"dependencies": {
// ...
},
"devDependencies": {
// ...
},
"scripts": {
"prepublish": "marked-man --name gulp docs/CLI.md > gulp.1",
"lint": "eslint . && jscs *.js bin/ lib/ test/",
"pretest": "npm run lint",
},
"engines": {
"node": ">= 0.9"
},
"license": "MIT"
}
so at the command line:
$ gulp default
will execute this:
"bin": {
"gulp": "./bin/gulp.js"
},
on the other hand, require('gulp') in your code will return the value of this:
https://github.com/gulpjs/gulp/blob/master/index.js
normally we see this in a package.json file as:
"main": "index.js"
but since this is the default, they just omitted it (which is dumb IMO, better to be explicit, but they aren't the first project I have seen take the lame shorthand route.).
Its occurs on Windows and usually one of the following fixes it:
If you didn't, run npm install gulp on the project folder, even if
you have gulp installed globally.
Normally, It isn't a problem on Windows, but it could be a issue with
the PATH. The package will try to get the PATH from the environment,
but you can override it by adding exec_args to your gulp settings.
For example, on Ubuntu:
"exec_args": {
"path": "/bin:/usr/bin:/usr/local/bin"
}
Hope It will be OK.
Source: https://github.com/NicoSantangelo/sublime-gulp/issues/12

Watch and rerun Jest JS tests

The Jest documentation suggests using npm test to execute tests.
Is there a way of watching your source and tests to rerun Jest tests automatically when relevant files have been changed?
Thanks to Erin Stanfill for pointing out, Jest already has support for automatically re-running. The better configuration for package.json would be
{
"scripts": {
"test": "jest"
}
}
To turn on the watch mode, just use
$ npm run test -- --watch
Or
$ yarn run test --watch
If you have npm test configured, you can just run npm test -- --watch.
As a complement suggestion you can add "--watchAll"
into your package.json file like this:
"scripts": {
"test": "jest --watchAll"
},
Each time you run npm test, the watch mode will be enable by default.
For more info npm CLI docs
Start you tests in watch mode.
jest --watch fileName.test.js
As per documentation
Run tests that match this spec name (match against the name in describe or test, basically).
jest -t name-of-spec
// or in watch mode
jest --watch -t="TestName"
This example shows how to use gulp to run your Jest tests using jest-cli, as well as a tdd gulp task to watch files and rerun Jest tests when a file changes:
var gulp = require('gulp');
var jest = require('jest-cli');
var jestConfig = {
rootDir: 'source'
};
gulp.task('test', function(done) {
jest.runCLI({ config : jestConfig }, ".", function() {
done();
});
});
gulp.task('tdd', function(done) {
gulp.watch([ jestConfig.rootDir + "/**/*.js" ], [ 'test' ]);
});
gulp.task('default', function() {
// place code for your default task here
});
install a couple of Grunt packages:
npm install grunt-contrib-watch grunt-exec --save-dev
make a Gruntfile.js with the following:
module.exports = function(grunt) {
grunt.initConfig({
exec: {
jest: 'node node_modules/jest-cli/bin/jest'
},
watch: {
files: ['**/*.js'],
tasks: ['exec:jest']
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-exec');
}
then simply run:
grunt watch
If you want to run a single file in watch mode:
yarn run test --watch FileName.test.jsx
I personally use the npm package jest-watch-typeahead.
You need to do 3 steps:
Install npm packege:
npm install --save-dev jest jest-watch-typeahead
Add to jest.config.js next code:
module.exports = {
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
};
Run Jest in watch mode
yarn jest --watch