How do I handle the new isCustomElement setup for using web components in Vue 3 when unit testing with Jest - vue.js

I am trying to write unit tests for my Vue 3 app using web components.
I have Jest configured containing transform options:
// ...
"transform": {
".*\\.(vue)$": "vue-jest",
"^.+\\.js$": "babel-jest"
},
// ...
I need to use isCustomElement which is now required at compilation time, so I’ve added options based on the proposed solution in Vue3 docs like I did in webpack. I played around with it in the transform and global options. And also tried adding it to my babel.config.
// ...
"transform": {
".*\\.(vue)$": ["vue-jest", {
compilerOptions: {
isCustomElement: tag => tag === 'my-custom-component'
}
}],
"^.+\\.js$": "babel-jest"
},
// ...
However it’s still throwing a Vue warn when running tests:
[Vue warn]: Failed to resolve component: my-custom-component.
Any ideas how to make isCustomElement work with Jest? I am at a loss as to what I need to set up to get rid of the console warnings and properly render the web components. In Vue 2 I just had to add them to setupFiles directly.

Related

Building nuxt 3 project missing some plugins stylings

I have a nuxt 3 project that is working fine on localhost while developing. I use FormKit and vue-toastification and everything is fine on "npm run dev".
But once I run npm run build to build it for deployment. lots of stylings are missing. Mainly those two plugins. the error messages for the forms by FormKit aren't red and not styled. vue-toastifications display with full height and width of the screen as it has no styling.
would I do any extra steps before running npm run build? like building these plugins or something?
this is my nuxt.config.ts file if it might help!
// #ts-nocheck
import Icons from "unplugin-icons/vite"
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
css: ["~/assets/fonts/droidkufi/droidarabickufi.css", "#formkit/themes/genesis"],
modules: [
"#nuxtjs/tailwindcss",
[
"#pinia/nuxt",
{
autoImports: ["defineStore"],
},
],
"#formkit/nuxt",
],
plugins: ["~/plugins/flowbite.client.ts", "~/plugins/i18n.ts"],
vite: {
plugins: [
Icons({
autoInstall: true,
}),
],
},
runtimeConfig: {
// secret serverside variables
public: {
// baseURL: "http://127.0.0.1:8000/api/",
// apiBase: "http://127.0.0.1:8000/api/",
// homeBase: "http://127.0.0.1:8000",
baseURL: "https://sju.davidlouis.co/api/",
apiBase: "https://sju.davidlouis.co/api/",
homeBase: "https://sju.davidlouis.co",
},
},
vue: {
compilerOptions: {
isCustomElement: (tag) => ["datepicker-hijri"].includes(tag),
},
},
})
I tried to run npm run dev back to test if styles are working. and yes they are working fine. the problem starts when I run npm run build for production and deployment.

Unable to load stencil components lib with Vue3 using Vite

I created a sample project to reproduce this issue: https://github.com/splanard/vue3-vite-web-components
I initialized a vue3 project using npm init vue#latest, as recommanded in the official documentation.
Then I installed Scale, a stencil-built web components library. (I have the exact same issue with the internal design system of my company, so I searched for public stencil-built libraries to reproduce the issue.)
I configured the following in main.ts:
import '#telekom/scale-components-neutral/dist/scale-components/scale-components.css';
import { applyPolyfills, defineCustomElements } from '#telekom/scale-components-neutral/loader';
const app = createApp(App);
app.config.compilerOptions.isCustomElement = (tag) => tag.startsWith('scale-')
applyPolyfills().then(() => {
defineCustomElements(window);
});
And the same isCustomElement function in vite.config.js:
export default defineConfig({
plugins: [vue({
template: {
compilerOptions: {
isCustomElement: (tag) => tag.startsWith('scale-')
}
}
})]
// ...
})
I inserted a simple button in my view (TestView.vue), then run npm run dev.
When opening my test page (/test) containing the web component, I have an error in my web browser's console:
failed to load module "http://localhost:3000/node_modules/.vite/deps/scale-button_14.entry.js?import" because of disallowed MIME type " "
As it's the case with both Scale and my company's design system, I'm pretty sure it's reproducible with any stencil-based components library.
Edit
It appears that node_modules/.vite is the directory where Vite's dependency pre-bundling feature caches things. And the script scale-button_14.entry.js the browser fails to load doesn't exist at all in node_modules/.vite/deps. So the issue might be linked to this "dependency pre-bundling" feature: somehow, could it not detect the components from the library loader?
Edit 2
I just found out there is an issue in Stencil repository mentioning that dynamic imports do not work with modern built tools like Vite. This issue has been closed 7 days ago (lucky me!), and version 2.16.0 of Stencil is supposed to fix this. We shall see.
For the time being, dropping the lazy loading and loading all the components at once through a plain old script tag in the HTML template seems to be an acceptable workaround.
<link rel="stylesheet" href="node_modules/#telekom/scale-components/dist/scale-components/scale-components.css">
<script type="module" src="node_modules/#telekom/scale-components/dist/scale-components/scale-components.esm.js"></script>
However, I can't get vite pre-bundling feature to ignore these imports. I configured optimizeDeps.exclude in vite.config.js but I still get massive warnings from vite when I run npm run dev:
export default defineConfig({
optimizeDeps: {
exclude: [
// I tried pretty much everything here: no way to force vite pre-bundling to ignore it...
'scale-components-neutral'
'#telekom/scale-components-neutral'
'#telekom/scale-components-neutral/**/*'
'#telekom/scale-components-neutral/**/*.js'
'node_modules/#telekom/scale-components-neutral/**/*.js'
],
},
// ...
});
This issue has been fixed by Stencil in version 2.16.
Upgrading Stencil to 2.16.1 in the components library dependency and rebuilding it with the experimentalImportInjection flag solved the problem.
Then, I can import it following the official documentation:
main.ts
import '#telekom/scale-components-neutral/dist/scale-components/scale-components.css';
import { applyPolyfills, defineCustomElements } from '#telekom/scale-components-neutral/loader';
const app = createApp(App);
applyPolyfills().then(() => {
defineCustomElements(window);
});
And configure the custom elements in vite config:
vite.config.js
export default defineConfig({
plugins: [vue({
template: {
compilerOptions: {
isCustomElement: (tag) => tag.startsWith('scale-')
}
}
})]
// ...
})
I did not configure main.ts
stencil.js version is 2.12.1,tsconfig.json add new config option in stencil:
{
"compilerOptions": {
...
"skipLibCheck": true,
...
}
}
add new config option in webpack.config.js :
vue 3 document
...
module: {
rules:[
...
{
test: /\.vue$/,
use: {
loader: "vue-loader",
options: {
compilerOptions: {
isCustomElement: tag => tag.includes("-")
}
}
}
}
...
]
}
...

Next.js: Jest encountered an unexpected token. Jest failed to parse a file. Crashing due to dot ( .{color: red} ) before a className in CSS files [duplicate]

I am trying to get my first Jest Test to pass with React and Babel.
I am getting the following error:
SyntaxError: /Users/manueldupont/test/avid-sibelius-publishing-viewer/src/components/TransportButton/TransportButton.less: Unexpected token
> 7 | #import '../variables.css';
| ^
My package.json config for jest look like this:
"babel": {
"presets": [
"es2015",
"react"
],
"plugins": [
"syntax-class-properties",
"transform-class-properties"
]
},
"jest": {
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "RelativeImageStub"
},
"testPathIgnorePatterns": [
"/node_modules/"
],
"collectCoverage": true,
"verbose": true,
"modulePathIgnorePatterns": [
"rpmbuild"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react/",
"<rootDir>/node_modules/react-dom/",
"<rootDir>/node_modules/react-addons-test-utils/",
"<rootDir>/node_modules/fbjs",
"<rootDir>/node_modules/core-js"
]
},
So what am I missing?
moduleNameMapper is the setting that tells Jest how to interpret files with different extension. You need to tell it how to handle Less files.
Create a file like this in your project (you can use a different name or path if you’d like):
config/CSSStub.js
module.exports = {};
This stub is the module we will tell Jest to use instead of CSS or Less files. Then change moduleNameMapper setting and add this line to its object to use it:
'^.+\\.(css|less)$': '<rootDir>/config/CSSStub.js'
Now Jest will treat any CSS or Less file as a module exporting an empty object. You can do something else too—for example, if you use CSS Modules, you can use a Proxy so every import returns the imported property name.
Read more in this guide.
I solved this by using the moduleNameMapper key in the jest configurations in the package.json file
{
"jest":{
"moduleNameMapper":{
"\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
}
}
}
After this you will need to create the two files as described below
__mocks__/styleMock.js
module.exports = {};
__mocks__/fileMock.js
module.exports = 'test-file-stub';
If you are using CSS Modules then it's better to mock a proxy to enable className lookups.
hence your configurations will change to:
{
"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"
},
}
}
But you will need to install identity-obj-proxy package as a dev dependancy i.e.
yarn add identity-obj-proxy -D
For more information. You can refer to the jest docs
UPDATE who use create-react-app from feb 2018.
You cannot override the moduleNameMapper in package.json but in jest.config.js it works, unfortunately i havent found any docs about this why it does.
So my jest.config.js look like this:
module.exports = {
...,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(scss|sass|css)$": "identity-obj-proxy"
}
}
and it skips scss files and #import quite well.
Backing my answer i followed jest webpack
Similar situation, installing identity-object-proxy and adding it to my jest config for CSS is what worked for me.
//jest.config.js
module.exports = {
moduleNameMapper: {
"\\.(css|sass)$": "identity-obj-proxy",
},
};
The specific error I was seeing:
Jest encountered an unexpected token
/Users/foo/projects/crepl/components/atoms/button/styles.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.button { }
^
SyntaxError: Unexpected token .
1 | import React from 'react';
> 2 | import styles from './styles.css';
If you're using ts-jest, none of the solutions above will work! You'll need to mock transform.
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
roots: [
"<rootDir>/src"
],
transform: {
".(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/jest-config/file-mock.js",
'.(css|less)$': '<rootDir>/jest-config/style-mock.js'
},
};
file-mock.js
module.exports = {
process() {
return `module.exports = 'test-file-stub'`;
},
};
style-mock.js
module.exports = {
process() {
return 'module.exports = {};';
}
};
I found this working example if you want more details.
Solution of #import Unexpected token=:)
Install package:
npm i --save-dev identity-obj-proxy
Add in jest.config.js
module.exports = {
"moduleNameMapper": {
"\\.(css|less|scss)$": "identity-obj-proxy"
}
}
Update: Aug 2021
If you are using Next JS with TypeScript. Simply follow the examples repo.
Else you will be wasting days configuring the environment.
https://github.com/vercel/next.js/tree/canary/examples/with-jest
I added moduleNameMapper at the bottom of my package.json where I configured my jest just like this:
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(scss|less)$": "<rootDir>/config/CSSStub.js"
}
}

Use optimized es6 build of MobX for React Native in Metro config

I'm trying to use the optimized, es6 build of Mobx, as per the documentation:
Tip: the main entry point of the MobX 5 package ships with ES5 code for backward compatibility with all build tools. But since MobX 5 runs only on modern browsers anyway, consider using the faster and smaller ES6 build: lib/mobx.es6.js. For example by setting up a webpack alias: resolve: { alias: { mobx: __dirname + "/node_modules/mobx/lib/mobx.es6.js" }}
https://mobx.js.org/README.html#browser-support
This allows me to import mobx and get the mobx.es6.js build:
import mobx from 'mobx' // Yay, es6 build!!!
This works great for Webpack-based projects, such as Electron ones, where I already have it working.
For React Native, I can specify extraNodeModules in metro.config.js like so:
module.exports = {
resolver: {
extraNodeModules: {
"mobx": path.resolve(__dirname, 'node_modules/mobx/lib/mobx.es6.js'),
},
},
};
...except that doesn't work, I presume, because the mobx dependency resolves fine on its own, and so this configuration option is never checked.
I can use a separate alias for mobx, such as mobx-es6 but that's not ideal, to put it nicely:
module.exports = {
resolver: {
extraNodeModules: {
// Nooo I don't want to update a bazillion source files!.
"mobx-es6": path.resolve(__dirname, 'node_modules/mobx/lib/mobx.es6.js'),
},
},
};
Is there some other way to configure Metro so that I can override the mobx import like I can with Webpack?
I'm using RN 0.60.0.
The solution is to add a browser section to package.json:
"name": "My React Native Project",
"version": "0.0.1",
"browser": {
"mobx": "mobx/lib/mobx.es6.js"
},
This is undocumented, AFAICT, but there are hints here:
resolverMainFields
Type: Array<string>
Specify the fields in package.json files that will be used by the module resolver to do redirections when requiring certain packages. For example, using ['browser', 'main'] will use the browser field if it exists and will default to main if it doesn't.
https://facebook.github.io/metro/docs/configuration#resolvermainfields
import mobx from 'mobx' // Yay, es6 build!!!

Laravel Mix and Vue custom Loader (iView)

I'm kinda new to programming with frameworks like VueJs and webpack is completely new for me. Right now we are working with Laravel 5.6 and laravel mix. I don't know if vue-loader is already in laravel.mix but I'm using a Vue Component Framework called iView and I need to load a custom Loader according to their page how to set it up: https://www.iviewui.com/docs/guide/iview-loader-en
The problem is it just doesn't work.
Nothing gets rendered and I get this error everytime:
[Vue warn]: Failed to mount component: template or render function not
defined.
Here's my webpack.mix.js
mix.webpackConfig({
module: {
rules: [
{
test: /\.vue$/,
use: [
{
loader: 'vue-loader',
options: {
}
},
{
loader: 'iview-loader',
options: {
prefix: true
}
}
]
}
]
}
})
But when I remove the section with loader: 'vue-loader' then everything gets rendered as it should but the custom loader is still not working since I get errors like this when using the kebap case name.
[Vue warn]: Unknown custom element: - did you register the
component correctly? For recursive components, make sure to provide
the "name" option.
Anyone good at Laravel who knows how to solve this? Thanks in advance.
cheers