Jest's test match does not pick my test files - jestjs

Hey I can't get testMatch to pick up my test file. Here's my config:
module.exports = {
preset: 'jest-puppeteer',
testMatch: [
'**/tests/**/?(*.)+spec.js'
]
};
My directory layout:
- Automation
- jest.config.js
- tests
- single-property
- index.spec.js
Output:
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In C:\Users\<user_name>\WebstormProjects\Automation
4 files checked.
testMatch: **/tests/**/?(*.)+spec.js - 0 matches
testPathIgnorePatterns: \\node_modules\\ - 4 matches
testRegex: - 0 matches
Pattern: - 0 matches

Try something like this:
'**/tests/**/*.spec.js'

add this to end of your package.json file
"jest": {
"globals": {
"ts-jest": {
"tsconfig": "tsconfig.json"
}
},
"moduleFileExtensions": ["ts","js"],
"transform": {
"^.+\\.(ts|tsx)$": "./node_modules/ts-jest/preprocessor.js"
},
"testMatch": [
"**/tests/**/*.spec.(ts|js)"
],
"testEnvironment": "node"
}

Related

babel-jest: Babel ignores app/utils/myfile.js - make sure to include the file in Jest's transformIgnorePatterns as well

I cannot get my jest tests to run when I have ignored a file with babel:
babel.config.js:
module.exports = {
ignore: ['./app/utils/myfile.js'],
presets: [
[
'#babel/preset-env',
{
targets: {
node: '14',
},
useBuiltIns: 'entry',
corejs: '3.8',
},
],
],
};
jest.config.js:
module.exports = {
coverageDirectory: 'coverage',
setupFiles: ['./jest.init.js'],
testEnvironment: 'node',
testMatch: ['**/?(*.)+(spec|test).js'],
transform: {
'^.+\\.(js|jsx)$': 'babel-jest',
},
transformIgnorePatterns: ['myfile'],
testPathIgnorePatterns: ['/node_modules/'],
};
i have added myfile.js to the babel ignore and to the jest transformIgnorePatterns. what could it be?

Jest: SyntaxError: Unexpected token 'export' happens at tslib.es6.js

I get this error:
C:\Users\myname\Projects\ConfigEditor\MesConfiguration.WebClient\node_modules\tslib\tslib.es6.js:24
export function __extends(d, b) {
^^^^^^
SyntaxError: Unexpected token 'export'
My jest-esm.config.mjs looks like this
const jestConfig = {
preset: 'jest-preset-angular/presets/defaults-esm',
extensionsToTreatAsEsm: ['.ts'],
globals: {
'ts-jest': {
useESM: true,
stringifyContentPathRegex: '\\.(html|svg)$',
tsconfig: '<rootDir>/tsconfig-esm.spec.json',
},
},
testEnvironment: 'jsdom',
moduleFileExtensions: ['ts', 'html', 'js', 'json', 'mjs'],
resolver: 'jest-preset-angular/build/resolvers/ng-jest-resolver.js',
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
transform: {
'^.+\\.(ts|js|mjs|html|svg)$': 'jest-preset-angular',
},
globalSetup: 'jest-preset-angular/global-setup',
moduleNameMapper: {
//tslib: 'tslib/tslib.mjs',
tslib: 'tslib/tslib.es6.js',
"#shared/(.*)": "<rootDir>/src/app/shared/$1",
"#editors/(.*)": "<rootDir>/src/app/editors/$1",
"#dashboard/(.*)": "<rootDir>/src/app/dashboard/$1",
"#env": "<rootDir>/src/environments/environment",
},
setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
}
export default jestConfig;
package.json has
"type": "module",
I start the test with
"test-esm": "node --experimental-vm-modules --no-warnings node_modules/jest/bin/jest.js -c=jest-esm.config.mjs --no-cache",
What ist wrong?
After renaming the tslib.es6.js to tslib.mjs the error is gone, but this is no solution. It should work after any yarn install
The error is gone because you have set
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)']
you are basically using the preset jest-preset-angular/presets/defaults-esm So most of the properties you are typing in the config are redundant
One thing is that the transformIgnorePatterns somehow does not work with multiple items in that array (in some cases) so it is better to put everything at once like in my case
transformIgnorePatterns: ['node_modules/(?!rxjs|tslib)']
here is my full jest.config.js and setup-jest.ts file I am using with Angular14 with the ESM execution node --experimental-vm-modules node_modules/jest/bin/jest.js
// jest-config.ts
module.exports = {
preset: 'jest-preset-angular/presets/defaults-esm',
testRegex: '.*spec.ts$',
transformIgnorePatterns: [
'node_modules/(?!rxjs|tslib)'
],
moduleNameMapper: {
"^dnd-core$": "dnd-core/dist",
"^react-dnd$": "react-dnd/dist",
"^react-dnd-html5-backend$": "react-dnd-html5-backend/dist",
"^react-dnd-touch-backend$": "react-dnd-touch-backend/dist",
"^react-dnd-test-backend$": "react-dnd-test-backend/dist",
"^react-dnd-test-utils$": "react-dnd-test-utils/dist"
},
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
};
// setup-jest.ts
import 'jest-preset-angular/setup-jest.mjs';
Object.defineProperty(window, "getComputedStyle", {
value: () => ["-webkit-appearance"]
});

Jest - Cannot generate cobertura coverage report for my projects

I'm using jest in a monorepo. I would like to generate a Cobertura report when testing a some of my projects.
Jest.config.base.js
module.exports = {
preset: '#vue/cli-plugin-unit-jest/presets/typescript-and-babel',
transform: {
'vee-validate/dist/rules': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
'^.+\\.(ts|tsx)$': 'ts-jest',
},
testMatch: [
'**/*.(spec|test).(js|jsx|ts|tsx)',
],
testEnvironmentOptions: {
// Allow test environment to fire onload event
// See https://github.com/jsdom/jsdom/issues/1816#issuecomment-355188615
resources: 'usable',
},
reporters: [
'default',
[
'jest-trx-results-processor',
{
outputFile: './coverage/test-results.trx',
defaultUserName: 'user name to use if automatic detection fails',
},
],
],
moduleFileExtensions: [
'js',
'ts',
'json',
'vue',
],
testURL: 'http://localhost/',
snapshotSerializers: [
'jest-serializer-vue',
],
runner: 'groups',
};
Jest.config (root)
const baseConfig = require('./jest.config.base')
module.exports = {
...baseConfig,
projects: [
'<rootDir>/apps/my-app',
'<rootDir>/apps/my-app-copy',
'<rootDir>/libs/my-lib',
],
coverageDirectory: '<rootDir>/coverage/',
};
Jest.config (my-app)
const baseConfig = require('../../jest.config.base');
const packageJson = require('./package.json');
module.exports = {
...baseConfig,
transformIgnorePatterns: [],
roots: [
'<rootDir>/src',
],
name: packageJson.name,
displayName: packageJson.name,
};
I did not paste other jest.config to save space, but they are similar.
What works
If I run jest --coverage --coverageReporters=cobertura, it will generate a Cobertura report, but all my projects will be tested.
What does not work
If I run jest --projects apps/my-app apps/my-app-copy --coverage --coverageReporters=cobertura, only test-results.trx is generated.
Question
How could I test only 2 projects out of 3, and generate a single Cobertura report for those?
I'm working on something similar in our monorepo and I was able to generate the cobertura report installing jest-junit and defining the reporters in the root jest.config like this
coverageReporters: ['html', 'text', 'text-summary', 'cobertura'],
Then I run jest --coverage

TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'

When Jest.js encounters import.meta in the code, I get an error:
FAIL testFile.test.ts
● Test suite failed to run
testFile.ts:40:10 - error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'.
40 return import.meta?.env as EnvironmentalVariablesType
I have installed the following babel related packages:
// package.json
"devDependencies": {
"#babel/core": "^7.16.5",
"#babel/preset-env": "^7.16.5",
"#babel/preset-typescript": "^7.16.5",
"#vitejs/plugin-react-refresh": "1.3.6",
"babel-jest": "^27.4.5",
"jest": "27.3.1",
"jest-environment-jsdom-global": "3.0.0",
"react": "17.0.1",
"ts-jest": "27.0.7",
"typescript": "4.1.3",
"vite": "2.6.14"
"dependencies": {
"babel-plugin-transform-vite-meta-env": "^1.0.3",
"babel-preset-vite": "^1.0.4",
I've setup babel.config.js as follows:
module.exports = {
plugins: [ 'babel-plugin-transform-vite-meta-env' ],
presets: [
[
'#babel/preset-env',
{ targets: { node: 'current' } },
],
[ '#babel/preset-typescript' ],
[ 'babel-preset-vite' ],
],
}
and my vite.config.js:
import { defineConfig } from 'vite'
import reactRefresh from '#vitejs/plugin-react-refresh'
import replace from '#rollup/plugin-replace'
// https://vitejs.dev/config/
export default defineConfig( {
base: '/time/',
server: {
port: 9000,
},
plugins: [
reactRefresh(),
replace( {
'process.env.NODE_ENV': JSON.stringify( 'development' ),
'process.env.SHOW_DEV_TOOLS': JSON.stringify( 'true' ),
} ),
],
} )
Tried
set module in tsconfig.json to es2020, esnext, or system
None of these cleared or changed the terminal error.
Is there some misconfiguration above that is preventing Jest from properly running babel?
In tsconfig.json, try setting the compilerOptions as so:
{
"compilerOptions": {
"module": "es2022",
"moduleResolution": "Node"
},
...
}
Install vite-plugin-environment plugin (https://www.npmjs.com/package/vite-plugin-environment)
Create .env file in your project root folder near package.json
provide your env variables in .env files
change all your import.meta.env.YOUR_VAR to process.env.YOUR_VAR
open vite.config.ts and list the vite-plugin-environment:
import EnvironmentPlugin from 'vite-plugin-environment';
...
plugins: [
react(),
...
EnvironmentPlugin('all')
]
Jest will understand process.env.YOUR_VAR, so if you change all your import.meta.env.YOUR_VAR to process.env.YOUR_VAR your test will pass without import.meta.env error
This article helped me for setting up Jest in my Vite project.
You can use the following command to run the test as per the jest documentation along with setting allowSyntheticDefaultImports to "true" in ts config file, these two changes solved the error for me.
yarn NODE_OPTIONS=--experimental-vm-modules npx jest
or
npm NODE_OPTIONS=--experimental-vm-modules npx jest
Ensure you have the relevant modules installed as per this. This article, have proper ts, jest and babel config added. (I have shared my config files for anyone who comes across this error. This article came in pretty handy to know about initial set-up requirements.)
//tsconfig.json
{
"compilerOptions": {
"target": "ES2020", /* Specify ECMAScript target version: '' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "ES2020", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"allowJs": true, /* Allow javascript files to be compiled. */
"allowSyntheticDefaultImports": true,
"strict": true, /* Enable all strict type-checking options. */
/* Module Resolution Options */
"moduleResolution": "Node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": "src", /* Base directory to resolve non-absolute module names. */
"types": [
"jest"
], /* Type declaration files to be included in compilation. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
},
"include": [
"src/**/*.ts",
"./src/**/*.js"
],
"exclude": [
"node_modules"
],
}
//babel.config.js
export default api => {
const isTest = api.env('test');
// You can use isTest to determine what presets and plugins to use.
return {
presets: [
[
'#babel/preset-env',
'#babel/preset-typescript',
{
'targets': {
'node': 'current',
},
},
]
],
};
};
//jest.config.js
/** #type {import('ts-jest/dist/types').InitialOptionsTsJest} */
export default {
preset: 'ts-jest',
testEnvironment: 'node',
testTimeout: 20000, //to resolve timeout error
roots: ['src'],
modulePaths: ['node_modules', '<rootDir>/src'],
testPathIgnorePatterns: [
'<rootDir>/node_modules/', "/__utils"
],
moduleDirectories: [
"src"
],
transform: {
"^.+\\.js?$": "babel-jest",
"^.+\\.ts?$": "ts-jest"
},
transformIgnorePatterns: [""], // you can add any module that you do not want to transform, The first pattern will match (and therefore not transform) files inside /node_modules.
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(js?|tsx?)$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
testEnvironment: "node",
"moduleNameMapper": {
"src/(.*)": "<rootDir>/src/$1"
},
globals: {
"ts-jest": {
"useESM": true
}
},
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
}
};
I switched from jest to vitest, which got rid of this error.
No changes to the test code were necessary.
For reference, this is my vitest.config.js:
import { defineConfig } from 'vite';
export default defineConfig({
test: {
globals: true,
environment: 'jsdom'
}
});

Jest testing with angular ionic storage is failing

Hi i am using angular 11 and ionic 5 ;
for ionic storage i am using #ionic/storage-angular:^3.0.6 module.
during jest unit tests i am getting
Cannot find module '#ionic/storage' from
'node_modules/#ionic/storage-angular/bundles/ionic-storage-angular.umd.js'
#ionic/storage-angular is a dependency in one of the service which i mocked
jest.confi.js has
transformIgnorePatterns: [
'./node_modules/(?!#ionic|ngx-socket-io/|!#ionic/storage-angular)'
]
spec file mocking the service
let storeServiceStub={
get:jest.fn().mockResolvedValue({})
};
await TestBed.configureTestingModule({
declarations: [ DataSyncComponent ],
providers:[
{ provide: StoreService, useValue: storeServiceStub },
]
})
.compileComponents();
#ionic/storage-angular is a of store service which i m replacing with stub;
testing env to repo bug
package.json
dependencies:{
...
"#ionic/storage-angular": "^3.0.6",
...
}
devDependencies:{
...
"jest": "^27.0.3",
"jest-preset-angular": "^9.0.1",
"#types/jest": "^26.0.23",
...
}
node v 14
os osx 11.2.2
I can fix it by adding the following configuration in my jest.config.js
moduleNameMapper: {
'^#ionic/storage': '<rootDir>/node_modules/#ionic/storage/dist/esm/index.d.ts',
},
Quite similar to the answer from #Ferraria. But the module name starts with the character ^ and the path ends in index.d.ts.
My complete configuration is
module.exports = {
"preset": "jest-preset-angular",
"setupFilesAfterEnv": ["<rootDir>/setup-jest.ts"],
"transformIgnorePatterns": [
"node_modules/(?!#ngrx|#ionic-native|#ionic)"
],
moduleNameMapper: {
'^#ionic/storage': '<rootDir>/node_modules/#ionic/storage/dist/esm/index.d.ts',
},
setupFiles: ["jest-canvas-mock"]
};
Provide the jest moduleNameMapper for #ionic/storage in your jest.config.js like this:
...,
transformIgnorePatterns: [
'./node_modules/(?!#ionic|ngx-socket-io/|!#ionic/storage-angular)'
],
"moduleNameMapper": {
"#ionic/storage": "<rootDir>/node_modules/#ionic/storage/dist/esm"
}
You can find more information for moduleNameMapper here.

Resources