Vite + Cypress : how to prevent reloading (due to optimized dependencies) causing the test to fail? - vue.js

When I'm running Cypress component test, sometimes i'm facing this :
17:34:59 [vite] ✨ new dependencies optimized: vuetify/components, vuetify/lib/components/VAppBar/index.mjs, vuetify/lib/components/VDivider/index.mjs, vuetify/lib/components/VToolbar/index.mjs, #vueuse/core
17:34:59 [vite] ✨ optimized dependencies changed. reloading
1) An uncaught error was detected outside of a test
And the test fails... If I relaunch tests a second time, everything is ok : all tests pass.
Anything I can do to prevent this ?
My cypress.config.ts is quite simple :
export default defineConfig({
video: false,
env: {
codeCoverage: {
exclude: ['cypress/**/*.*', 'src/**/*.cy.ts'],
},
},
component: {
devServer: {
framework: 'vue',
bundler: 'vite',
},
setupNodeEvents(on, config) {
registerCodeCoverageTasks(on, config)
return config
},
},
})
So do my vite.config.ts :
export default defineConfig({
plugins: [
vue(), // SFC
vuetify({
autoImport: true,
}),
istanbul({
cypress: true,
requireEnv: false,
}),
],
resolve: {
alias: {
'#': resolve(__dirname, 'src'),
},
extensions: ['.js', '.json', '.jsx', '.mjs', '.ts', '.tsx', '.vue'],
},
}
})

Related

Exclude certain folders in Vite and Rollup with Vue.js

I am using Vite to bundle my Vue.js app, I have #vitejs/plugin-vue and #rollup/plugin-typescript installed.
I would like Vite to skip bundling certain folders inside my src folder:
src > assets
...
src > skins
src > skins > skin1
**src > skins > skin2**
I have tried the exclude option in the vue and typescript plugins, neither work for me. Here is my vite.config.js:
const config = {
mode: process.env.MODE,
root: PACKAGE_ROOT,
resolve: {
alias: {
'/#/': join(PACKAGE_ROOT, 'src') + '/',
},
},
plugins: [vue({
exclude: ['**skin2'],
})],
base: '',
server: {
fs: {
strict: true,
},
},
build: {
sourcemap: true,
target: `chrome${chrome}`,
outDir: 'dist',
assetsDir: '.',
rollupOptions: {
input: join(PACKAGE_ROOT, 'index.html'),
external: [
...builtinModules.flatMap(p => [p, `node:${p}`]),
],
plugins: [
typescript({
exclude: ['**/skin2'],
}),
],
},
}
};
I also tried RegExp which also didn't work, what I've missed? Thank you!

Vite.js Dynamic Image Loading Fails In Production

I have a problem in importing dynamic assets in production mode. When I ran the development environment everything works fine and the assets loads...but when I build the Vue.js application, assets won't load and I gets below error:
TypeError: URL constructor: ../../../assets/images/name.png is not a valid URL.
how can I fix this issue?
Vue Example
<img :src="findImageFromNumber(card.cartNumber)" alt="image" width="25" />
function findImageFromNumber(number: string) {
const name = identify(number).english;
const path = new URL('../../../assets/images/banks/' + name + '.png', import.meta.url);
return path.href
}
Vite.js Config
export default defineConfig({
root: './',
resolve: {
alias: {
'/#/': path.resolve(__dirname, 'src')
},
},
publicDir: 'assets',
mode: 'production',
build: {
outDir: 'dist',
sourcemap: true,
target: ['es2019', 'safari11', 'firefox60', 'chrome61', 'node12'],
chunkSizeWarningLimit: 500,
minify: false,
emptyOutDir: true,
assetsInlineLimit: 2048,
rollupOptions: {
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`,
manualChunks(id) {
if (id.includes('vue')) {
return 'react';
} else if (id.includes('node_modules')) {
return 'vendor';
}
},
},
}
},
plugins: [
vue(),
legacy({
polyfills: ['es.promise.finally', 'es/map', 'es/set'],
modernPolyfills: ['es.promise.finally']
})
],
})
Note: Everything works fine in development and it only fails in production...
Assets is your public dir. Should it just be /assets/images/banks, according to the docs?

karma+webpack+typescript+mocha require is not defined

I try to configure my environment to run tests on node.
This my my webpack.config.test.js
const serverConfig = {
module: {
loaders: [
{test: /\.tsx?$/, loader: 'ts-loader' }
]
},
target: 'node',
externals:[nodeExternals()],
resolve: {
extensions: ['.ts', '.tsx', '.js']
}
};
module.exports = serverConfig;
karma.config.js
// Karma configuration
// Generated on Tue Jun 27 2017 07:20:43 GMT-0500 (Hora est. Pacífico, Sudamérica)
const webpackConfig=require('./config/webpack/webpack.test');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha','es6-shim'],
plugins:[
require("karma-es6-shim"),
'karma-webpack',
'karma-jsdom-launcher',
'karma-mocha',
'karma-spec-reporter',
'karma-jsdom-launcher',
'karma-coverage',
'karma-chrome-launcher',
"karma-phantomjs-launcher",
'karma-htmlfile-reporter'
],
files: [
'test/**/*.spec.ts'
],
coverageReporter: {
webpackMiddleware: {
stats: "errors-only"
},
dir: 'build/coverage/',
reporters: [
{ type: 'html' },
{ type: 'text' },
{ type: 'text-summary' }
]
},
// list of files to exclude
exclude: [
],
preprocessors: {
'test/**/*.spec.ts':["webpack","coverage"]
},
webpack:webpackConfig,
reporters: ['spec','progress','html'],
htmlReporter: {
outputFile: 'tests/units.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'A sample project description',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
// web server port
port: 9876,
colors: true,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
})
}
test1
import { DBCONFIG } from './../src/config/db.config';
import { CONEXION } from './../src/config/database/mongo';
import { expect } from 'chai';
describe("#DATABASE",()=>{
it("Esta conectado",()=>{
CONEXION("hola",DBCONFIG.MONGO_URL_LOCAL)
.then(()=>{
expect(1).to.be("1");
})
.catch((e)=>{
expect(1).to.be(e);
})
})
});
test2
import { expect } from 'chai';
describe("#User",()=>{
it("use2r",()=>{
expect(1).to.equal("1");
})
})
When I run mocha + webpack with mocha-webpack, there is no problem the tests are running.
package.json
"test-server": "mocha-webpack --timeout 1000 --webpack-config config/webpack/webpack.test.js test/**/*.spec.ts",
"test":"karma start"
When I do it from karma depending on which browser I use to display the messages I throw similar errors, when I throw it with jsdom or PhantomJS I throw the following
require is not defined o Cannot find
Looking in git, the only answer that solved the problem, is to put in the processors of karma the following.
'test/**/*.spec.ts':["webpack","coverage"]
It is the same way and I have varied, but the error continues.

I could not import exported variables from an es2015 NPM module

I have an npm module named sidebar. I use webpack to compile the es2015 src files into a single file. So far running webpack does not output any problem and creates a file, lib/sidebar.min.js
I have set the it to be the main file in package.json
...
"description": "",
"main": "lib/sidebar.min.js",
"scripts": {
...
I have this in my src/index.js file
export const foo = 'foo'
export const bar = 'bar'
I tried using this module in my main project
import { foo, bar } from 'sidebar'
console.log(foo)
console.log(bar)
Both console log calls outputs undefined
After searching the internet for hours, I am totally stumped as to why this is a problem.
Any ideas?
EDIT: Here is the webpack config for the main repository
var webpackConfig = {
entry: {
app: './src/app/main.app.js',
vendor: ['angular']
},
output: {
path: DIST_DIRECTORY + '/scripts/',
publicPath: '/scripts/',
filename: '[name].min.js',
chunkFilename: '[name].min.js'
},
devtool: 'source-map',
module: {
loaders: [{
test: /\.js$/,
loader: 'babel'
}, {
test: /\.html$/,
loader: 'raw'
}]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true,
dead_code: true
},
sourceMap: true
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js")
],
devServer: {
contentBase: DIST_DIRECTORY + '/'
}
};

Syntax error when testing React component Jasmine and Webpack

I keep getting an error when trying to run a simple test using React, Karma, Jasmine and Webpack. The error is ' Uncaught SyntaxError: Unexpected token < ', I think my jsx isn't being processed to js, but I don't know why that is happening as I understand webpack should handle that using the babel loader. If anyone can provide advice I would be grateful
Here are my files
karma.conf.js
var webpack = require("webpack"),
path = require("path");
// Karma configuration
module.exports = function(config) {
config.set({
basePath: "",
frameworks: ["jasmine"],
files: [
"../test/!**!/!*.test.js"
],
preprocessors: {
"./test/!**!/!*.test.js": ["webpack"]
},
webpack: {
module: {
loaders: [
{
test: /\.jsx?$/i,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{ test: /\.less$/, loader: "style!css!less" }
]
},
},
plugins: [
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
])
],
resolve: {
root: __dirname,
extensions: [
'',
'.json',
'.js',
'.jsx'
]
}
},
webpackMiddleware: {
noInfo: true
},
plugins: [
require("karma-webpack"),
require("karma-jasmine"),
require("karma-chrome-launcher")
],
reporters: ["dots"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["Chrome"],
singleRun: false
});
};
my test file example.test.js
var Comp = require('../../../js/common/components/MyComp.jsx'),
React = require('react'),
TestUtils = React.addons.TestUtils;
describe("Component Test", function() {
it("renders an h1", function () {
var component = TestUtils.renderIntoDocument(
<Comp/> // syntax error here
);
var h2 = TestUtils.findRenderedDOMComponentWithTag(
component, 'h2'
);
expect(h1).toExist();
});
});
So the syntax error happens at < Comp... . Thanks!
Apologise it was an error in setting the correct path to the test file.
files: [
"../test/**/*.test.js"
],
preprocessors: {
"../test/**/*.test.js": ["webpack"]
},