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

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 ;)

Related

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

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.

Jest import common plugins like Vee Validate before each test

I'm new to Jest and am testing my Nuxt JS application with unit testing. I have many test files set up and need to import various logic into each test file, such as my Vee Validate config.
I've tried adding it to a setup.js file and included this in setupFilesAfterEnv but it's not getting included.
What am I doing wrong?
tests/unit/setup.js
import Vue from 'vue'
import { ValidationProvider, ValidationObserver, extend, configure, localize } from 'vee-validate'
import * as rules from 'vee-validate/dist/rules';
import en from 'vee-validate/dist/locale/en.json'
const config = {
mode: 'lazy',
classes: {
valid: '',
invalid: 'tw-border-red-500 dark:tw-border-white'
}
}
Object.keys(rules).forEach(rule => {
extend(rule, rules[rule]);
});
configure(config)
// Register it globally
Vue.component('ValidationObserver', ValidationObserver)
Vue.component('ValidationProvider', ValidationProvider)
// // activate the locales
localize({
en
});
My jest.config.js file:
module.exports = {
silent: true,
testEnvironment: 'jsdom',
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
'^vue$': 'vue/dist/vue.common.js',
},
moduleFileExtensions: ['js', 'vue', 'json'],
transform: {
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
'vee-validate/dist/rules': 'babel-jest'
},
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/**/*.vue',
],
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!vee-validate/dist/rules)',
],
setupFilesAfterEnv: [
'<rootDir>/tests/unit/setup.js'
]
}
And one of my test files called LoanAmount is:
import { mount } from '#vue/test-utils'
import flushPromises from 'flush-promises';
import LoanAmount from '#/components/Form/Steps/Loan/LoanAmount'
describe('LoanAmount', () => {
test('is a Vue instance', () => {
const wrapper = mount(LoanAmount)
expect(wrapper.vm).toBeTruthy()
})
test('amount is available for value', async () => {
const wrapper = mount(LoanAmount)
await flushPromises()
const amount = wrapper.findAll('.jest__amount-input')
expect(amount.exists()).toBe(true)
})
})
If I include all of the contents from tests/unit/setup.js and include above my describe block then it works, but I can't be repeating this in each test file.
You can use the setupFiles property in jest.config.js:
module.exports = {
rootDir: path.resolve(__dirname, '../../'),
moduleFileExtensions: [
'js',
'json',
'vue'
],
transform: {
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'vee-validate/dist/rules': 'babel-jest'
},
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!(vuetify)|(vue-material-design-icons)|(vee-validate/dist/rules)|(vue-picture-input/PictureInput.vue))'
],
setupFiles: [
'./tests/unit/jest.setup.js'
],
reporters: ['default', 'jest-junit'],
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/**/Application/*.js'
],
testPathIgnorePatterns: [
'<rootDir>/node_modules/',
'<rootDir>/vendor/',
'<rootDir>/web/'
],
coverageThreshold: {
global: {
branches: process.env.COVERAGE_THRESHOLD_GLOBAL_BRANCH || 37,
functions: process.env.COVERAGE_THRESHOLD_GLOBAL_FUNCTIONS || 40,
lines: process.env.COVERAGE_THRESHOLD_GLOBAL_LINES || 50
}
}
}

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.

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

karma config with browserify/babel

I have a karma conf that I try to make work with babel/browserify. It looks like this:
module.exports = function(config) {
config.set({
browsers: ['Chrome'],
frameworks: ['jasmine'],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-babel-preprocessor',
'karma-browserify'
],
preprocessors: {
'../src/**/*.js': ['babel', 'browserify'],
'unit/*.spec.js': ['babel', 'browserify']
},
files: [
'../src/**/*.js',
'unit/*.spec.js'
],
babelPreprocessor: {
options: {
presets: ['es2015'],
sourceMap: 'inline'
},
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
}
}
});
};
Every time I run this configuration through gulp babel preprocessor returns the following error:
ERROR [preprocessor.babel]: Cannot read property 'bundleFile' of undefined
Try adding 'browserify' to 'frameworks', like this:
frameworks: ['browserify', 'jasmine']
I had the same error, fixed by doing this. Here's my working karma config
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
singleRun: true,
frameworks: ['browserify', 'mocha'],
reporters: ['dots'],
files: ['./*test.js'],
preprocessors: {
'*.js': ['browserify']
},
logLevel: 'LOG_DEBUG',
browserify: {
debug: true,
transform: [ ['babelify', {presets: ['es2015', "react"]} ] ]
}
});
};
The fixed config file:
module.exports = function(config) {
config.set({
browsers: ['Chrome'],
frameworks: ['jasmine', 'browserify'],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-babel-preprocessor',
'karma-browserify'
],
preprocessors: {
'../src/js/app.js': ['browserify'],
'../src/js/login/login-ctrl.js': ['browserify'],
'./unit/*.spec.js': ['browserify']
},
files: [
'../../node_modules/angular/angular.js',
'../../node_modules/angular-mocks/angular-mocks.js',
'../src/js/app.js',
'../dist/js/partials/templates-all.js',
'../src/js/login/login-ctrl.js',
'unit/*.spec.js'
],
browserify: {
debug: true,
transform: [
['babelify']
]
},
singleRun: false,
reporters: ['progress'],
colors: true
});
};