Jest module not defined - node.js

I'm writing my first package and I just converted it to be TypeScript compatible, but this somehow affected my GitHub workflow. When I run my tests using Jest locally, they work just fine. When my tests are run on GitHub, it succeeds for 10.x, but not 12.x or 14.x, giving me the following error:
(node:2397) ExperimentalWarning: The ESM module loader is experimental.
ReferenceError: module is not defined
at file:///home/runner/work/enhancedMathJS/enhancedMathJS/jest.config.js:1:1
at ModuleJob.run (internal/modules/esm/module_job.js:146:37)
at async Loader.import (internal/modules/esm/loader.js:182:24)
at async readConfigFileAndSetRootDir (/home/runner/work/enhancedMathJS/enhancedMathJS/node_modules/jest-config/build/readConfigFileAndSetRootDir.js:126:32)
at async readConfig (/home/runner/work/enhancedMathJS/enhancedMathJS/node_modules/jest-config/build/index.js:217:18)
at async readConfigs (/home/runner/work/enhancedMathJS/enhancedMathJS/node_modules/jest-config/build/index.js:406:26)
at async runCLI (/home/runner/work/enhancedMathJS/enhancedMathJS/node_modules/#jest/core/build/cli/index.js:230:59)
at async Object.run (/home/runner/work/enhancedMathJS/enhancedMathJS/node_modules/jest/node_modules/jest-cli/build/cli/index.js:163:37)
npm ERR! Test failed. See above for more details.
enhancedmath#2.0.0 test /home/runner/work/enhancedMathJS/enhancedMathJS
jest
File jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['<rootDir>/**/__tests__/**/*.spec.ts'],
testPathIgnorePatterns: ['/node_modules/'],
coverageDirectory: './test-reports',
coveragePathIgnorePatterns: ['node_modules', 'src/database', 'src/test', 'src/types'],
reporters: ['default', 'jest-junit'],
globals: { 'ts-jest': { diagnostics: false } },
};
Workflow
name: Node.js CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [10.x, 12.x, 14.x]
steps:
- uses: actions/checkout#v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node#v1
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm test
I don't understand what the problem is, since everything works locally, but not for every version of Node.js on GitHub.
If you want to check out the files and errors for yourself, you can find my repository here.

I use esm in my project. And config { type: "module" } in file package.json. So just change module.exports = to export default.

I got it working by installing ts-node and updating my jest.config.js file to a jest.config.ts file:
npm i --save-dev ts-node
Jest config
export default {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['<rootDir>/**/__tests__/**/*.spec.ts'],
testPathIgnorePatterns: ['/node_modules/'],
coverageDirectory: './coverage',
coveragePathIgnorePatterns: ['node_modules', 'src/database', 'src/test', 'src/types'],
reporters: ['default', 'jest-junit'],
globals: { 'ts-jest': { diagnostics: false } },
transform: {},
};

I got the very similar error ReferenceError: module is not defined in ES module scope when running Jest in ESM context.
This did the trick for me:
Change
module.exports = {
/* config here */
}
to
export default {
/* config here */
}
in jest.config.js.
Most tutorials and the config scaffolding that comes with Jest make the config a CJS module which will lead to the above error if you use it in ESM context.

Related

Why is there an error during build next.js project?

**my node.js.yml file
**
name: Node.js CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps:
- uses: actions/checkout#v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node#v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm ci
- run: npm run build
- run: npm run export
- name: Deploy 🚀
uses: JamesIves/github-pages-deploy-action#v4
with:
branch: gh-pages
folder: out # The folder the action should deploy.
enter image description here
error here
link to my repository
https://github.com/EduardKop/web-cv-next
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
distDir: 'build',
images: {
loader: 'akamai',
path: '',
}
}
module.exports = nextConfig
i wrote next.config.js config. I made a commit, then set up the action as indicated above in the yaml file and got an error
You should give the path of images, in error says that path can't be less that 0 char.
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
distDir: 'build',
images: {
loader: 'akamai',
path: '',
}
}
module.exports = nextConfig
You should write path in path attribute.

How do I use `unpkg` with ViteJS?

I'm migrating my Vue plugin from Vue CLI to Vitejs.
With vue-cli-service build I generate three files: index.common.js, index.umd.js and index.umd.min.js
In package.json I refer to these files with:
"main": "dist/index.common.js",
"unpkg": "dist/index.umd.min.js",
But now migrating to ViteJS npm run build creates js files with random strings index.25e1eb44.js.
How do I use unpkg with ViteJS in package.json?
By reading other code, I found a good solution:
import { defineConfig } from 'vite';
import vue from '#vitejs/plugin-vue';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
const path = require('path');
// https://vitejs.dev/config/
export default defineConfig({
build: {
lib: {
entry: path.resolve(__dirname, 'src/index.js'),
name: 'VueResponsiveVideoBackgroundPlayer',
fileName: 'vue-responsive-video-background-player',
},
rollupOptions: {
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// Add external deps here
globals: {
vue: 'Vue',
},
},
},
},
plugins: [
vue(),
cssInjectedByJsPlugin(),
],
});
For more, read here: https://vitejs.dev/config/build-options.html#build-commonjsoptions

BitBucket Jest tests get stuck

When pipeline gets to the tests (jest). It just stays there and spinner keeps spinning and nothing happens, no error messages. The test run in local with no errors.
After googling i noticed people suggest to use --maxWorkers=20% in jest due to cpu/memory issues. But it didnt help.
Triggering the tests in webpack like this:
"test": "jest --coverage --watchAll --maxWorkers=20% --maxConcurrent=2 --verbose --config=configs/jest.json",
I have this pipeline setup in bitbucket:
image: node:16
pipelines:
default:
- step:
name: Build
caches:
- node
script:
- npm install
- npm run build
- npm run test
artifacts:
- dist/**
- step:
name: Deploy to S3
deployment: production
trigger: manual
script:
- pipe: atlassian/aws-s3-deploy:1.1.0
variables:
AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
AWS_DEFAULT_REGION: 'eu-west-1'
S3_BUCKET: 'myname'
LOCAL_PATH: 'dist'
- step:
name: Invalidate CloudFront cache
trigger: automatic
script:
- pipe: atlassian/aws-cloudfront-invalidate:0.6.0
variables:
AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
DISTRIBUTION_ID: 'E3HTTJFUB2KUCW'
Here is the jest config file if it matters.
{
"rootDir": "..",
"testEnvironment": "jsdom",
"coverageDirectory": "<rootDir>/tests/__coverage__/",
"setupFiles": [
"<rootDir>/tests/__mocks__/shim.js"
],
"roots": [
"<rootDir>/src/",
"<rootDir>/tests/"
],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/tests/__mocks__/fileMock.js",
"\\.(css|scss|less)$": "<rootDir>/tests/__mocks__/styleMock.js"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx"
],
"transformIgnorePatterns": [
"/node_modules/"
],
"testRegex": "/tests/.*\\.(ts|tsx)$",
"moduleDirectories": [
"node_modules"
],
"globals": {
"DEVELOPMENT": false,
}
}
--watchAll=false should get you out of the menu.

Can't run wallaby.js with jest in vscode

I have a project with jest and typescript. When I run jest, the tests run correctly.
I prepared the wallaby.config.js file:
// wallaby.config.js
export default function () {
return {
autoDetect: true,
trace: true,
files: ['src/**', '!**/*Spec.ts'],
tests: ['__tests__/**/*Spec.ts'],
debug: true,
env: {
type: 'node',
runner: 'node',
},
};
}
When I try to start I get:
Failed to initialize wallaby jest. 
Failed to read Jest configuration from '.': m is not defined 
My packages.json as type = "module"
Also, my jest.config.js looks like:
export default {
verbose: true,
testMatch: ['<rootDir>/__tests__/**/*.ts'],
preset: 'ts-jest',
testEnvironment: 'node',
};
As I said at begin, if I type npx jest works correctly.
I want wallaby working on my vscode.
Finally I found a workaround.
First of all install jasmine and esm as dev dependency.
Now update the wallay.config.js file:
export default function configure(wallaby) {
return {
trace: true,
files: ['src/**', '!**/*Spec.ts'],
tests: ['__tests__/**/*Spec.ts'],
debug: true,
testFramework: 'jasmine', // <- added
env: {
type: 'node',
runner: 'node',
params: { //
runner: `-r esm`, // <- added
}, //
},
};
}
Now all work. I'm running test manually with jest and wallaby is using jasmine. It doesn't seem best way but works for now.

jest coverageDirectory configuration for project inside monorepo

I have a typescript monorepo with jest. Their jest.config.js is
module.exports = {
clearMocks: true,
projects: ['<rootDir>/packages/**/jest.config.js'],
collectCoverage: true,
coverageReporters: [
"text-summary",
"lcov",
],
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['*.spec.ts', '*.spec.tsx']
}
At the server package I create the jest.config.js with
const { name } = require('./package.json');
module.exports = {
displayName: name,
name,
'transform': {
'^.+\\.ts$': 'ts-jest'
},
collectCoverageFrom: [
'<rootDir>/src/**/*.ts'
],
coverageDirectory: '<rootDir>/packages/server/src/tests/coverage',
}
But when I run jest it creates the coverage directory at the root of my monorepo.
I just try to use coverageDirectory: '<rootDir>/src/tests/coverage',, coverageDirectory: 'src/tests/coverage', and coverageDirectory: [__dirname, 'src', 'tests', 'coverage'].join('/'), without success.
The only way I could change the path of coverage directory was to specify it at the jest.config.js of the monorepo, but with this I am unable to specify a coverage directory to each project.
Somebody knows how can I specify a different coverage directory for each project at a monorepo?
You can only specify a different coverage directory for each project if you are running jest for each product individually. If you are using a global config (the jest.config.js at the root of your monorepo) then the same coverage settings are applied across them all, including the coverage output directory.

Resources