jest-preset-angular not working with Angular 13 and ESM module - jest-preset-angular

I'm using ESM modules with jest and when compiling with angular 12 jest-preset-angular worked great for me by listing #igniteui in the exclusion list. I upgraded to Angular 13, and the Next version of jest-preset-angular, but I can't get it working now. Following the help page I tried to use this:
require('jest-preset-angular/ngcc-jest-processor')
module.exports = {
preset: 'jest-preset-angular/presets/defaults-esm',
moduleFileExtensions: ['ts', 'html', 'js', 'json', 'mjs'],
resolver: 'jest-preset-angular/build/resolvers/ng-jest-resolver.js',
transformIgnorePatterns: [
"node_modules/(?!#igniteui|tslib|.*\\.mjs$)"
],
transform: {
'^.+\\.(ts|js|mjs|html|svg)$': 'jest-preset-angular'
},
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts']
}
When I run jest it says it can't find the igniteui module. This is the jest.config.js I was using with the older version:
require('jest-preset-angular/ngcc-jest-processor')
module.exports = {
preset: 'jest-preset-angular/presets/defaults-esm',
globals: {
'ts-jest': {
useESM: true,
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.html$'
}
},
testTimeout: 20000,
transformIgnorePatterns: [
"node_modules/(?!#igniteui|tslib)"
],
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts']
}

I finally got it working by doing this:
require('jest-preset-angular')
module.exports = {
preset: 'jest-preset-angular/presets/defaults-esm',
transformIgnorePatterns: [
"node_modules/(?!#igniteui|#infragistics|tslib)"
],
moduleFileExtensions: ['ts', 'html', 'js', 'json', 'mjs'],
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts']
}
For those libraries giving you the bad import errors, add them to the transformIgnorePatters. You just need the prefix. So, for example, I'm using #infragistics/igniteui-angular but I only added #infragistics.

Related

vue-pdf-embed Inline worker is not supported on jest

I am using Vue 3 + Jest 28.
I've decided do try vue-pdf-embed, which worked great.
The problem is when I run jest.
It says
Inline worker is not supported
With this I can't proceed and got stuck.
My jest.config.ts looks like this:
const esModules = ['quasar', 'quasar/lang', 'lodash-es', 'cnpj'].join('|');
module.exports = {
verbose: true,
testEnvironment: 'jsdom',
testEnvironmentOptions: {
url: 'http://localhost/',
customExportConditions: ['node', 'node-addons'],
},
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tests/tsconfig.json',
isolatedModules: true,
},
},
collectCoverageFrom: ['src/**/*.{vue,js,ts}', '!src/*.{js,ts}', '!**/typings/**', '!src/**/definitions/*.ts'],
coverageProvider: 'v8',
setupFiles: [
'<rootDir>/tests/jest.init.ts',
],
setupFilesAfterEnv: ['<rootDir>/tests/setupTests.ts'],
moduleFileExtensions: [
'vue',
'js',
'ts',
'json',
'jsx',
'tsx',
],
transform: {
// See https://jestjs.io/docs/en/configuration.html#transformignorepatterns-array-string
[`^(${esModules}).+\\.js$`]: 'babel-jest',
'^.+\\.(ts|js|html)$': 'ts-jest',
// vue-jest uses find-babel-file, which searches by this order:
// (async) .babelrc, .babelrc.js, package.json, babel.config.js
// (sync) .babelrc, .babelrc.js, babel.config.js, package.json
// https://github.com/tleunen/find-babel-config/issues/33
'.*\\.vue$': '#vue/vue3-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
},
transformIgnorePatterns: [`node_modules/(?!(${esModules}))`],
moduleNameMapper: {
'#/(.*)$': '<rootDir>/src/$1',
'^quasar$': 'quasar/dist/quasar.esm.prod.js',
'lodash-es': 'lodash',
},
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
};
I've tried so far to add it to the esModules variable I have in my jest config but no success
I came with a reasonable answer: mock the component:
In jest.init.ts, which I refer to in my jest.config.ts above, I put the following:
jest.mock('vue-pdf-embed', () => () => '<mock-vue-pdf-embed/>');
and now everything works just fine ;)

vue plugin pwa sw.js not found

I have 1 app using the vue pwa plugin, it works great.
The vuejs config for the app looks like this:
const WebpackNotifierPlugin = require('webpack-notifier')
module.exports = {
lintOnSave: false,
css: {
loaderOptions: {
sass: {
implementation: require('sass')
}
}
},
transpileDependencies: [
'vuex-module-decorators',
'vuex-persist'
],
pwa: {
name: 'MyApp',
themeColor: '#000000',
msTileColor: '#000000',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: 'black',
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'dev/sw.js',
// ...other Workbox options...
}
},
configureWebpack: {
devServer:{
historyApiFallback: true,
},
plugins: [
new WebpackNotifierPlugin(),
],
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: 3,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `npm.${packageName.replace('#', '')}`;
},
},
},
},
},
},
}
I have another app, exactly the same, vue2, beufy etc etc.. i installed the same stuff via the vue pwa plugin and the config looks exactly the same but when i run build it says it cannot find the sw.js file:
Error: ENOENT: no such file or directory, open 'dev/sw.js'
I have created a uber basic vue app which does the same thing here: https://github.com/johndcarmichael/vue-pwa-sw-not-found
Has anyone else got this issue, and how did you resolve it?
You are not having dev/sw.js in your project, as you set in swSrc. InjectManifest means take this sw.js source file and write precache manifest into it, producing the final service-worker.js file.

Using vue and jest to testing svg inline

I have problem with testing view when I use image inline in code
'src/assets/icons/circle-small.svg?inline'
I have versions:
- babel-jest: 23.6.0
- vue: 2.6.10
Configuration:
Vue CLI:
const svgRule = config.module.rule('svg');
svgRule.oneOf('inline').use('vue-svg-loader').loader('vue-svg-loader').end();
Jest config:
moduleFileExtensions: [
'js',
'vue',
],
transform: {
'^.+\\.vue$': 'vue-jest',
'^.+\\.js$': '<rootDir>/babel-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg)$': 'jest-transform-stub',
},
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
},
I import in view:
import Img from '#/assets/icons/img.svg?inline';
I getting configuration error:
Could not locate module #/assets/icons/circle-small.svg?inline mapped as:
/some/src/assets/icons/circle-small.svg?inline.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/^#\/(.*)$/": "/some/src/$1"
},
"resolver": null
}
I have a problem with configuring tests for the case when I import inline image. Can anyone know what else i should to configure or what library to use?
I found a solution, it was enough to modify regex
this was wrong:
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg)$': 'jest-transform-stub',
and this is correct:
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)(\\?inline)?$': 'jest-transform-stub',
First, by using jest moduleNameMapper function, remove ?inline
moduleNameMapper: {
'^.+/(.*\\.svg)\\?inline$': '<rootDir>/path/svg/$1'
},
For my case
import SvgBack from '../../assets/svg/back.svg?inline'
(Convert to) --->
import SvgBack from '../../assets/svg/back.svg'
Second, transform the svg files into vuejs format
transform: {
'^.+\\.svg$': '<rootDir>/svgTransform.js',
},
svgTransform.js can find it in the guide https://github.com/visualfanatic/vue-svg-loader/blob/master/docs/faq.md#how-to-use-this-loader-with-jest
jest.config.js
module.exports = {
collectCoverage: false,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/*.vue',
],
// tell Jest to handle `*.vue` files
moduleFileExtensions: [ 'js', 'json', 'vue' ],
moduleNameMapper: {
'^.+/(.*\\.svg)\\?inline$': '<rootDir>/assets/svg/$1',
},
modulePaths: [ '<rootDir>' ],
snapshotSerializers: [ '<rootDir>/node_modules/jest-serializer-vue' ],
transform: {
// process `*.vue` files with `vue-jest`
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
// process js with `babel-jest`
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
// process svg with svgTransform.js
'^.+\\.svg$': '<rootDir>/tests/tools/svgTransform.js',
},
watchman: false,
}
know this thread is very old but got here searching for a solution so will anwser as my solution is a bit different from the other ones and for me simple enough to resolve my problem.
vue: 3.0.0
vue-jest: 5.0.0-0
Just added this config to jest.config.js:
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)(\\?inline)?$': '<rootDir>/tests/mocks/fileMock.js'
}
and added the fileMock.js file:
export default 'test-file-stub'
jest now will load that string and stop give error when I import svg as a component.
This resolves only the error, to check some class on the inline svg the test-file-stub needs to step up for some kind of template, really depends if needed.

nuxtjs issue with IE11 compatibility_ object assign

I am suffered by IE compatibility. (my vue version is 3.1.0, nuxt is 2.3.4)
It keeps error with Object.assign. Here is the list what I have tried.
babel-preset-vue-app(https://www.npmjs.com/package/babel-preset-vue-app). Heard that it does not support vue2.X. I followed the description on this post. It gets an error while building source.
Adding babel-polyfill in nuxt.config.js. It does not error, but still I got Object.assign error on the page.
Install babel/plugin-transform-object-assign. It also does not make any error in build process, but got Object assign thing in the page.
Is there any option I can try to feet IE11 compatibility?
Here is my current .babelrc and nuxt.config.js.
.babelrc
{
"presets": [
[
"env",
{
"modules": false
}
],
[ "vue-app",
{
"useBuiltIns": true,
"targets": {
"ie": 9,
"uglify": true
}
}
]
],
"plugins": [
"#babel/plugin-transform-object-assign",
"transform-vue-jsx",
[
"module-resolver",
{
"root": [
"./src"
],
"alias": {
"~sbdc": "./src/sbdc"
}
}
]
]
}
build option in nuxt.config.js
build: {
babel: {
presets: [
['vue-app', {
useBuiltIns: true,
targets: { ie: 9, uglify: true }
}
]
]
},
optimization: {
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/](babel-polyfill|moment|lodash|axios|get-size|jquery|js-cookie|jwt-decode|numeral|vuetify)[\\/]/,
name: 'utilityVendor'
}
}
}
},
output: {
publicPath: serviceConfig.pwa_publicPath || false
},
extractCSS: true,
plugins: [
new webpack.ProvidePlugin( {
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
} )
]
}
Thanks for sharing you solutions!
======= Edited in 0114 =============
Etra information #1.
When I look at the error on ie11 browser, it automatically transform code like below
return {layout:"popup",data:[{resultBody:Object.assign(Object.create(null), ... sorry, sensitive data
while the original code is...
asyncData: async function ({req}) {
return {
resultBody: req.body,
};
},
req.body is supported by body-parser.
After hours of struggling, I solved this with not good way(In my thought).
I just add object-assign polyfill js to nuxt.js
module.exports = {
...
head: {
script: [ { src: '/js/object-assign.js' } ]
},
...
};
But I still want to know the proper way to apply babel-polyfill into nuxt project.

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"]
},