I'm writing some tests for a React Native app written in TS and currently trying to migrate to jest.mocked instead of using the mocked export from ts-jest/utils (which is required in order to move past jest v27). I get the following error though and have tried all sorts of things to try and fix it, but with no luck.
Your test environment does not support `mocked`, please update it.
54 |
55 | beforeEach(() => {
> 56 | jest.mocked(Icon).mockReturnValue(null)
| ^
57 | })
58 |
59 | afterEach(() => {
at Object.mocked (node_modules/jest-runtime/build/index.js:2204:19)
// babel.config.js
module.exports = {
plugins: [
[
'module-resolver',
{
extensions: ['.js', '.jsx', '.ts', '.tsx'],
root: ['.'],
},
],
'transform-inline-environment-variables',
['#babel/plugin-proposal-decorators', { legacy: true }],
'react-native-reanimated/plugin',
],
presets: [
'module:metro-react-native-babel-preset',
['#babel/preset-react', { runtime: 'automatic' }],
],
}
// jest.config.js
module.exports = {
preset: 'react-native',
collectCoverage: false,
coveragePathIgnorePatterns: ['/node_modules/', '.*.test..*'],
coverageReporters: ['text'],
coverageThreshold: {
global: {
branches: 100,
},
},
forceExit: true,
globals: {
'ts-jest': {
babelConfig: '<rootDir>/babel.config.js',
diagnostics: false,
isolatedModules: true,
},
},
moduleFileExtensions: [
'gql',
'ts',
'tsx',
'js',
'jsx',
'json',
'node',
'csv',
],
modulePaths: ['<rootDir>'],
modulePathIgnorePatterns: modulesToIgnore,
resetMocks: false,
resetModules: false,
setupFilesAfterEnv: ['<rootDir>/__tests__/setup/index.ts'],
testMatch: [
'<rootDir>/__tests__/**/*.test.ts?(x)',
'<rootDir>/src/**/?(*.)test.ts?(x)',
],
testPathIgnorePatterns: ['<rootDir>/node_modules', ...modulesToIgnore],
transform: {
'^.+\\.jsx?$': 'babel-jest',
'^.+\\.tsx?$': 'ts-jest',
},
transformIgnorePatterns: [
`<rootDir>/node_modules/(?!${modulesNeedingTransform.join('|')})`,
],
verbose: true,
}
Nothing is standing out to me as immediately obvious for what's keeping jest.mocked from being available.
Related
I need to configure my babel.config.js to use react-native-vision-camera as:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'react-native-reanimated/plugin',
{
globals: ['__scanCodes'],
},
],
],
};
but my current configuration is as:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
'nativewind/babel',
'react-native-reanimated/plugin',
[
'module-resolver',
{
root: ['./src'],
extensions: [
'.ios.ts',
'.android.ts',
'.ts',
'.ios.tsx',
'.android.tsx',
'.tsx',
'.jsx',
'.js',
'.json',
],
alias: {
'^#src/(.+)': './src/\\1',
'^#assets/(.+)': './src/assets/\\1',
'^#components/(.+)': './src/components/\\1',
'^#contexts/(.+)': './src/contexts/\\1',
'^#models/(.+)': './src/models/\\1',
'^#navigation/(.+)': './src/navigation/\\1',
'^#screens/(.+)': './src/screens/\\1',
'^#services/(.+)': './src/services/\\1',
'^#utils/(.+)': './src/utils/\\1',
},
},
],
],
};
Where to put my globals?
All the configurations I have tried are not working
Thanks!
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
'nativewind/babel',
['react-native-reanimated/plugin',
{
globals: ['__scanCodes'],
}
],
[
'module-resolver',
{
root: ['./src'],
extensions: [
'.ios.ts',
'.android.ts',
'.ts',
'.ios.tsx',
'.android.tsx',
'.tsx',
'.jsx',
'.js',
'.json',
],
alias: {
'^#src/(.+)': './src/\\1',
'^#assets/(.+)': './src/assets/\\1',
'^#components/(.+)': './src/components/\\1',
'^#contexts/(.+)': './src/contexts/\\1',
'^#models/(.+)': './src/models/\\1',
'^#navigation/(.+)': './src/navigation/\\1',
'^#screens/(.+)': './src/screens/\\1',
'^#services/(.+)': './src/services/\\1',
'^#utils/(.+)': './src/utils/\\1',
},
},
],
],
};
the trick is that reanimated warns to use their plugin LAST!!
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
'nativewind/babel',
[
'module-resolver',
{
root: ['./src'],
extensions: [
'.ios.ts',
'.android.ts',
'.ts',
'.ios.tsx',
'.android.tsx',
'.tsx',
'.jsx',
'.js',
'.json',
],
alias: {
'^#src/(.+)': './src/\\1',
'^#assets/(.+)': './src/assets/\\1',
'^#components/(.+)': './src/components/\\1',
'^#contexts/(.+)': './src/contexts/\\1',
'^#models/(.+)': './src/models/\\1',
'^#navigation/(.+)': './src/navigation/\\1',
'^#screens/(.+)': './src/screens/\\1',
'^#services/(.+)': './src/services/\\1',
'^#utils/(.+)': './src/utils/\\1',
},
},
],
[
'react-native-reanimated/plugin',
{
globals: ['__scanCodes'],
},
],
],
};
File Structure:
public
- assets
src
other file
Svelte.config.js
resolve: {
alias: {
"#": resolve(__dirname, "src"),
$assets: resolve(__dirname, "public/assets"),
},
},
Jest.config.cjs
const sveltePreprocess = require("svelte-preprocess");
module.exports = {
transform: {
"^.+\\.svelte$": ["svelte-jester", [sveltePreprocess()]],
"^.+\\.js$": "babel-jest",
"^.+\\.(png|svg)$": "<rootDir>/svgTransform.js",
},
moduleFileExtensions: ["js", "svelte"],
bail: false,
verbose: true,
testPathIgnorePatterns: ["node_modules"],
transformIgnorePatterns: ["node_modules"],
moduleDirectories: ["node_modules"],
setupFilesAfterEnv: ["#testing-library/jest-dom/extend-expect"],
moduleNameMapper: {
"#/(.*)$": "<rootDir>/src/$1",
"$assets/(.*)$": "<rootDir>/public/assets/$1",
},
setupFiles: ["<rootDir>/setupTests.js"],
testResultsProcessor: "jest-sonar-reporter",
testTimeout: 30000,
testEnvironment: "jsdom",
};
Usage:
import SvgClose from "$assets/svg/close.svg";
Error:
Cannot find module '$assets/svg/close.svg' from 'src/components/atoms/Modal.svelte'
# work fine but $assets not working .
What changes I should do in jest.config.cjs
or I am Missing something?
I am trying to create code coverage for VUE files using typescript in karma and webpack.
I am using istanbul-instrumenter-loader as a post process after but keep getting.
Everything works okay for pure .ts files, but when incluiding vue files I get
build failed (from ./node_modules/istanbul-instrumenter-loader/dist/cjs.js):
TypeError: Cannot read property 'fileCoverage' of undefined
When debugging istanbul-instrumenter-loader I noticed that
ee.exit(path); is undefined because the VUE files are being instrumented 3 times, the first two work okay but the third one is the one that crashes.
this is my webpack config
module.exports = {
node: {
fs: 'empty'
},
mode: 'development',
devtool: 'inline-source-map',
stats: 'verbose',
resolve: {
alias: {
Home: path.resolve( __dirname ),
Client: path.resolve( __dirname, 'client/' ),
ClientUtils$: path.resolve( __dirname, 'client/utils/index.utils.client.ts' ),
Views: path.resolve( __dirname, 'client/views/' ),
Components: path.resolve( __dirname, 'client/components/' ),
Constants$: path.resolve( buildPath, 'shared/constants.js' )
},
extensions: [
'.scss',
'.js',
'.ts',
'.vue'
]
},
module: {
rules: [
{
test: /\.vue$/,
use: [
{
loader: 'vue-loader'
}
]
},
{
test: /\.ts?$/,
exclude: /node_modules/,
use: [
{
loader: 'cache-loader'
},
{
loader: 'thread-loader',
options: {
workers: Math.max(require('os').cpus().length - 1, 1)
}
},
{
loader: 'ts-loader',
options: {
transpileOnly: true,
happyPackMode: true,
appendTsSuffixTo: [/\.vue$/]
}
}
]
},
{
test: /\.js$/,
exclude: [/dist/, /node_modules/, /coverage_server/, /coverage_client/],
loader: 'babel-loader'
},
{
test: /\.ts$/,
include: [/client/],
exclude: [
/node_modules/,
/\.spec\.ts$/,
/server/
],
enforce: 'post',
loader: 'istanbul-instrumenter-loader',
options: {
esModules: true
}
},
{
test: /\.(s*)css$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
}
]
},
plugins: [
new VueLoaderPlugin()
};
and my karma.conf is
module.exports = function(config) {
let files = [];
if (config.grep) {
files.push({ pattern: config.grep, type: 'module' });
} else {
files.push('client/index.client.spec.ts');
}
config.set({
frameworks: ["mocha", "chai", "sinon"],
files,
preprocessors: {
'client/**/*spec.ts': ['webpack', 'sourcemap']
},
webpack: require('./webpack.test.js'),
reporters: ['spec', 'dots', 'html', 'coverage-istanbul'],
browsers: ['ChromeHeadless'],
coverageReporter: {
dir: './coverage_client',
includeAllSources: true,
reporters: [{ type: 'lcov', subdir: '.' }, { type: 'text' }]
},
coverageIstanbulReporter: {
reports: ['text', 'lcov' ],
dir: './coverage_client',
fixWebpackSourcePaths: true,
'report-config': {
html: { outdir: 'html' }
}
},
htmlReporter: {
outputDir: 'karma_client_html', // where to put the reports
templatePath: null, // set if you moved jasmine_template.html
focusOnFailures: true, // reports show failures on start
namedFiles: false, // name files instead of creating sub-directories
pageTitle: null, // page title for reports; browser info by default
urlFriendlyName: false, // simply replaces spaces with _ for files/dirs
reportName: 'report_summary_filename', // report summary filename; browser info by default
// experimental
preserveDescribeNesting: false, // folded suites stay folded
foldAll: false // reports start folded (only with preserveDescribeNesting)
}
});
};
and my tsconfig is
{
"compilerOptions": {
"incremental": true,
"outDir": "./build/",
"target": "es2018",
"module": "CommonJS",
"lib": ["es2018", "dom", "dom.iterable"],
"allowSyntheticDefaultImports": true,
"inlineSourceMap": true,
"sourceMap": false,
"noImplicitAny": false,
"strict": true,
"alwaysStrict": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"types": [ "node", "mocha", "chai" ],
"baseUrl": ".",
"paths": {
"type-graphql": ["./node_modules/type-graphql/dist/browser-shim.ts"],
"Client/*": ["./client/*"],
"ClientUtils": ["./client/utils/index.utils.client.js"],
"Views/*": ["./client/views/"],
"Components/*": ["./client/components/*"],
"Constants": ["./shared/constants.ts"]
}
},
"include": [
"./client/**/*.ts",
"./client/**/*.vue",
"./server/**/*.ts",
"./shared/**/*.ts"
],
"exclude": [
"**/*.spec.ts",
"node_modules"
],
"files": ["./vue-shims.d.ts"]
}
Bug report on ElementUI
I am using On-demand loading of ElementUI components. I've followed the instructions correctly and it works just fine when running the app.
The problem arises when I try to test with Jest and Vue test utils. None of the components I am importing seem to be found, so I get this error when running my tests:
ReferenceError: _Message is not defined
I get the same error for any of the other components, that my test touches.
On the bug report I mentioned above, I am being suggested that my babel configuration is not being applied in my testing environment? Or its something about my Jest configuration. I've tried various things to fix this:
Doing a manual mocks
Spying on the component
Importing the whole ElementUI package inside my test
Updating Jest configuration
Nothing seems to work and I have no idea what is wrong...
bebel.config.js
module.exports = {
presets: [
'#vue/app',
],
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk',
},
],
],
};
jest.config.js
module.exports = {
// roots: ['<rootDir>/src/', '<rootDir>/tests/'],
moduleFileExtensions: [
'js',
'jsx',
'json',
'vue',
],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest',
},
transformIgnorePatterns: [
'/node_modules/(?!element-ui)',
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
'^.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
},
snapshotSerializers: [
'jest-serializer-vue',
],
testMatch: [
'**/tests/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)',
],
testURL: 'http://localhost/',
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
collectCoverage: true,
coverageReporters: ['lcov', 'text-summary'],
};
I have a couple of suggestions for you here:
change this in jest.config.js
module.exports = {
moduleFileExtensions: [
'js',
'jsx',
'json',
'vue',
],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.(js|jsx)?$': 'babel-jest'
},
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
'^.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
},
snapshotSerializers: [
'jest-serializer-vue',
],
testMatch: [
'**/tests/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)',
],
testURL: 'http://localhost/',
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
collectCoverage: true,
coverageReporters: ['lcov', 'text-summary'],
};
and this in babel.config.js
module.exports = {
presets: [
'#vue/app',
],
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk',
},
],
],
"env": { "test": { "plugins": ["transform-es2015-modules-commonjs", "dynamic-import-node"] } }
};
Also I believe #babel/plugin-transform-modules-commonjs is needed in yarn.
Let me know if this works.
I am trying to use Karma, Jasmine, JSPM, and Babel all together. It seems I am getting an error I am not sure how to trace:
12 04 2016 19:59:04.407:ERROR [preprocessor.babel]: [BABEL] /Users/allen/work/twentytwenty.qualboard/src/TwentyTwenty.QualBoard.Web/wwwroot/config.js: Unknown option: base.preset. Check out http://babeljs.io/docs/usage/options/ for more info
It barks about config.js and the option base.preset. I am not sure why thought I have done a complete project search for base.preset and cannot find its existence.
Karma Config:
module.exports = function(config) {
config.set({
autoWatch: false,
babelPreprocessor: {
options: {
preset: ['es2015'],
sourceMap: 'inline',
},
},
basePath: '',
browsers: [
'PhantomJS',
],
colors: true,
concurrency: Infinity,
coverageReporter: {
type: 'html',
dir: 'converage/',
},
exclude: [],
files: [],
frameworks: [
'jspm',
'jasmine',
],
jspm: {
config: './wwwroot/config.js',
packages: './wwwroot/jspm_packages',
loadFiles: [
'test/**/*.js',
],
serveFiles: [
'test/**/*.js',
],
},
logLevel: config.LOG_INFO,
plugins: [
'karma-babel-preprocessor',
'karma-coverage',
'karma-jasmine',
'karma-jspm',
'karma-phantomjs-launcher',
'karma-spec-reporter',
],
port: 9876,
preprocessors: {
'./wwwroot/config.js': ['babel'],
'./wwwroot/aurelia/**/*.js': ['babel'],
'./wwwroot/test/**/*.js': ['babel', 'coverage'],
},
proxies: {
'/wwwroot/': '/TwentyTwenty.Qualboard.Web/wwwroot/',
'/jspm_packages/': '/wwwroot/jspm_packages',
},
reporters: [
'coverage',
'spec',
],
singleRun: true,
specReporter: {
maxLogLines: 1,
suppressErrorSummary: true,
suppressFailed: false,
suppressPassed: false,
supressSkipped: false,
},
});
};
My BabelRc:
{
"presets": ["es2015"]
}
I am starting Karma in the terminal by doing:
karma start
What am I missing?
You have a typo, it is presets and not preset:
babelPreprocessor: {
options: {
presets: ['es2015'],
sourceMap: 'inline',
},
}