Setting up jest report in gitlab ci - jestjs

Can you tell me how can I set up the jest-junit reporter?
Expected behavior: Appearances on the page of the merge request description of errors.
Real behavior: when it crashes, jobs are just red icons.
script:
- yarn install
- yarn add --dev jest-junit
- yarn affected:test --ci --base=remotes/origin/master --reporters=default --reporters=jest-junit
artifacts:
when: always
expire_in: 5 days
reporters:
junit:
- junit.xml
jest.config.ts:
{
"reporters": [ "default", "jest-junit" ]
}
package.json:
},
"jest-junit": {
"outputDirectory": "junit"
}
} ```
// start jest > "affected:test": "nx affected:test --parallel --maxParallel=4"
What can be fixed? Thanks in advance!

Related

bump2version fails to find the current release tag

I've been upgrading our workflow to add an automatic version bump. The problem is that I accidentally added these steps with a typo in the .bumpversion.cfg file and from that moment, the workflow is sure that the releases start at tag 1.0.0. I've created 2 releases with this scenario (1.0.0 and 1.0.1). Once I was on to this, I deleted the two releases (and tags), but now the workflow can't find the latest release tag.
One important piece of info is that the repo is a Node app, so there is already a package.json and such there.
I tried:
bumping manually the versions in my files
bumping with bump2version to the version I expected
bumping with bump2version to the next version
As you'll see, the command is missing the current version. The error in the workflow is:
An error occurred while running semantic-release: Error: Command failed with exit code 2: bump2version --allow-dirty --current-version --new-version 1.0.0 patch
the create release step is:
name: Create new release
on:
workflow_dispatch:
push:
branches:
- main
jobs:
release:
runs-on: ubuntu-latest
if: "github.event_name == 'push' && github.ref == 'refs/heads/main' && !startsWith(github.event.head_commit.message, 'chore')"
steps:
- name: Checkout code
uses: actions/checkout#v3
with:
fetch-depth: 0
token: ${{ secrets.ADMIN_TOKEN }}
- name: setup nodejs
uses: actions/setup-node#v3
with:
node-version: '16'
- name: release using semantic-release
env:
GITHUB_TOKEN: ${{ secrets.ADMIN_TOKEN }}
GIT_AUTHOR_NAME: secrets.automation.dev
GIT_AUTHOR_EMAIL: secrets.automation.dev#il.ibm.com
GIT_COMMITTER_NAME: secrets.automation.dev
GIT_COMMITTER_EMAIL: secrets.automation.dev#il.ibm.com
run: |
sudo apt-get update
sudo apt-get install python
pip install --user bumpversion
npm install #semantic-release/changelog
npm install #semantic-release/exec
npm install #semantic-release/git
npm install #semantic-release/github
npx semantic-release
The .bumpversion.cfg is:
[bumpversion]
current_version = 1.0.40
commit = True
message = Update version {current_version} -> {new_version}
[bumpversion:file:package.json]
search = {current_version}
replace = {new_version}
The .releaserc file is:
{
"debug": true,
"branches": [ "main" ],
"plugins": [
["#semantic-release/commit-analyzer", {
"preset": "angular",
"releaseRules": [
{"type": "release","release": "patch"}
]}],
"#semantic-release/release-notes-generator",
"#semantic-release/changelog",
[
"#semantic-release/exec",
{
"prepareCmd": "bump2version --allow-dirty --current-version ${lastRelease.version} --new-version ${nextRelease.version} patch"
}
],
[
"#semantic-release/git",
{
"message": "chore(release): ${nextRelease.version} [skip ci] release notes\n\n${nextRelease.notes}"
}
],
"#semantic-release/github"
]
}
I used 2 things to fix the issue:
I followed the excellent fix by #alvaropinot from this issue thread. Basically, I had to force-tag the commit I expected to be with the latest tag and push the tags:
git tag -f v1.0.40 356a7b4
git push -f --tags
For #semantic-release/npm to work, I had to rename a secret from "NPM_AUTH_TOKEN" to "NPM_TOKEN".
After that, I revamped my semantic-release workflow to use #semantic-release/npm:
name: Create a new release
on:
workflow_dispatch:
push:
branches:
- main
jobs:
release:
runs-on: Ubuntu-20.04
if: "github.event_name == 'push' && github.ref == 'refs/heads/main' && !startsWith(github.event.head_commit.message, 'chore')"
steps:
- name: Checkout code
uses: actions/checkout#v3
with:
fetch-depth: 0
token: ${{ secrets.ADMIN_TOKEN }}
- name: setup nodejs
uses: actions/setup-node#v3
with:
node-version: '16'
- name: release using semantic-release
env:
GITHUB_TOKEN: ${{ secrets.ADMIN_TOKEN }}
GIT_AUTHOR_NAME: ***
GIT_AUTHOR_EMAIL: ***
GIT_COMMITTER_NAME: ***
GIT_COMMITTER_EMAIL: ***
NPM_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
run: |
sudo apt-get update
sudo apt-get install python
pip install --user bumpversion
npm install #semantic-release/changelog
npm install #semantic-release/git
npm install #semantic-release/github
npm install #semantic-release/npm
npx semantic-release
and the .releaserc file now looks like:
{
"debug": true,
"branches": [
"main"
],
"verifyConditions": [
"#semantic-release/changelog",
"#semantic-release/npm",
"#semantic-release/git"
],
"analyzeCommits":[
["#semantic-release/commit-analyzer", {
"preset": "angular",
"releaseRules": [
{"type": "release","release": "patch"}
]}],
],
"generateNotes": [
"#semantic-release/release-notes-generator"
],
"prepare": [
"#semantic-release/changelog",
"#semantic-release/npm",
"#semantic-release/git"
],
"publish": [
[
"#semantic-release/npm",
{
"pkgRoot": "dist"
}
],
{
"path": "#semantic-release/github"
}
]
}

Why doesn't Jest configuration defined by 'testMatch' option match any of my test files within my project?

This is how my Jest config file looks:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>'],
moduleDirectories: ['node_modules', 'server'],
globals: {
'ts-jest': {
tsconfig: './tsconfig.test.json',
},
},
watchPathIgnorePatterns: ['/node_modules'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
testMatch: ['/**/*.test.(ts|tsx)'],
globalSetup: './global-setup.js',
};
and this is the output I get when I run jest -c jest.config.js in the project's root directory:
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In C:\Users\xxx\Documents\xxx\xxx\xxx
432 files checked.
testMatch: /**/*.test.(ts|tsx) - 0 matches
testPathIgnorePatterns: \\node_modules\\ - 432 matches
testRegex: - 0 matches
Pattern: - 0 matches
I had a feeling this might be related to different path separators on Windows and Linux. I'm running on Windows. So I tried changing the testMatch to ['\\**\\*.test.(ts|tsx)'] in jest.config.js. That did not resolve my issue.
I have 2 NPM scripts defined inside my package.json that produce the same output as above:
"lint-and-test": "npm run lint && npm run test"
"test": "jest --coverage --verbose"
This has been a known issue for a while with Jest. See the Issue titled testMatch on Windows #7914 for more context.
In windows default slash for file paths look like one\two\three\file.test.ts, but Jest does not seem to internally convert \\(escaped Windows style) or /(Unix style) path separators correctly thereby resulting in not picking up any of the test files.

Azure Pipeline - Caching NPM - Jest Unexpected token ]

I have a monorepo with Lerna and yarn workspaces. I use Azure Devops to build and publish the application.
Commands
"emis-app:test": "yarn --cwd apps/my-app test", is located on the root package.json
What works
When there is a cache miss or when I don't cache NPM modules,
yarn my-app:test which then trigger yarn --cwd apps/my-app test is successful
What does not work
When the cache is used yarn emis-app:test which then triggers yarn --cwd apps/my-app test does not work and tests are failing.
Here is the output of the cache hit
Resolving key:
- **/yarn.lock, !**/node_modules/**/yarn.lock, !*... [file pattern; matches: 4]
- s/apps/my-app/yarn.lock --> 0E8B2ACAB9CF0A6F80305D0BD6C99FDFA703EE248C33DB254DF57F46CC67B6AF
- s/apps/my-app-1/yarn.lock --> 95AB055F93FBE7A5E118B9C1391F81E1E9885D5ED5F0B6EAAB46985D0619C81D
- s/libs/my-lib/yarn.lock --> C8B48CB9F78F4AAE95941EE10588B139FEE51E2CEDA3313E7FE2B78A32C680B0
- s/yarn.lock --> 31D5354CDC72614EEE3B29335A5F6456576FAEF27417B811967E7DDA9BD91E48
Workspaces
"workspaces": {
"packages": [
"apps/*",
"libs/*"
]
}
Each app is a vue application. Each app contains its own package.json, babel.config, jest.config etc.
jest.config.base extended in each app.
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 (my-app)
const baseConfig = require('../../jest.config.base');
const packageJson = require('./package.json');
module.exports = {
...baseConfig,
transformIgnorePatterns: [],
roots: [
'<rootDir>/src',
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
'^#libs/registration-lib/(.*)$': '<rootDir>/../../libs/registration-lib/src/$1',
},
name: packageJson.name,
displayName: packageJson.name,
};
Questions
Am I using the cache correctly?
Is it possible to use the caching when working with workspaces
Errors
FAIL #apps/my-app src/ui/views/pages/registration/individual/Individual.vue.spec.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
SyntaxError: Unexpected token ] in JSON at position 467
at JSON.parse (<anonymous>)
at parse (../../node_modules/tsconfig/src/tsconfig.ts:195:15)
at readFileSync (../../node_modules/tsconfig/src/tsconfig.ts:181:10)
at Object.loadSync (../../node_modules/tsconfig/src/tsconfig.ts:151:18)
at find (../../node_modules/vue-jest/lib/load-typescript-config.js:33:39)
at loadTypescriptConfig (../../node_modules/vue-jest/lib/load-typescript-config.js:73:26)
at compileTypescript (../../node_modules/vue-jest/lib/compilers/typescript-compiler.js:9:20)
at processScript (../../node_modules/vue-jest/lib/process.js:23:12)
at Object.module.exports [as process] (../../node_modules/vue-jest/lib/process.js:42:18)
at ScriptTransformer.transformSource (../../node_modules/#jest/transform/build/ScriptTransformer.js:453:35)
Pipeline YAML
- task: NodeTool#0
inputs:
versionSpec: '15.x'
displayName: 'Install Node.js'
- task: Cache#2
displayName: Cache yarn packages
inputs:
key: '**/yarn.lock, !**/node_modules/**/yarn.lock, !**/.*/**/yarn.lock'
path: $(Build.SourcesDirectory)/node_modules
cacheHitVar: CACHE_HIT
- task: Yarn#3
condition: ne(variables['CACHE_HIT'], 'true')
inputs:
customRegistry: 'useFeed'
customFeed: ${{ parameters.packageFeed }}
arguments: --frozen-lockfile
displayName: 'Install NPM dependencies'
- script: yarn my-app:test
displayName: "Test My App"

Playwright test with NX

I have an NX workspace with a single application called my-app. I would like to run Playwright tests for my-app application by using NX console. Currently NX doesn't support Playwright plugin, so I've created a custom NX executor according to this tutorial. I've created necessary files for executor. After, I registered custom e2e command in application's project.json file. The playwright configuration file stays in the my-app folder.
When I run nx run my-app:e2e, the executor is been executed, however for some reason, playwright doesn't start. Instead, I see an error.
When I run manually in the console the command triggered by nx run my-app:e2e which is npx playwright test --config=apps/my-app/playwright.config.ts the playwright starts and does necessary testing.
project.json
...
...
...
"e2e": {
"executor": "./tools/executors/playwright:playwright",
"options": {
"path": "apps/my-app/playwright.config.ts"
}
}
executor.json
{
"executors": {
"playwright": {
"implementation": "./impl",
"schema": "./schema.json",
"description": "Runs Playwright Test "
}
}
}
impl.ts
export default async function echoExecutor(
options: PlaywrightExecutorOptions,
context: ExecutorContext
) {
console.info(`Executing "Playwright"...`);
console.info(`Options: ${JSON.stringify(options, null, 2)}`);
const { stdout, stderr } = await promisify(exec)(
`npx playwright test --config=${options.path}`,
);
console.log(stdout);
console.error(stderr);
const success = !stderr;
return { success };
}
schema.json
{
"$schema": "http://json-schema.org/schema",
"type": "object",
"cli": "nx",
"properties": {
"path": {
"type": "string",
"description": "Path to the project"
}
}
}
package.json
{
"executors": "./executor.json"
}
I'm not sure but maybe the problem is in promisify? I'm trying to call npx with it. Maybe there is a different way to call npx in this context?
const { stdout, stderr } = await promisify(exec)(
`npx playwright test --config=${options.path}`,
);
I will recommend https://github.com/marksandspencer/nx-plugins/tree/main/packages/nx-playwright
You will need to install the plugin using
yarn add --dev #mands/nx-playwright
yarn playwright install --with-deps
Remove existing e2e app nx generate remove <APP-NAME>-e2e before generating a new one
Generate new e2e app
yarn nx generate #mands/nx-playwright:project <APP-NAME>-e2e --project <APP-NAME>
PS: I am also author of the plugin
I would suggest to use https://github.com/marksandspencer/nx-plugins/tree/main/packages/nx-playwright
It should work out of the box
Try to use pnpm nx ...
Firstly, in package.json define:
"scripts": {
"test": "playwright test --output build --workers 2",
"test:debug": "playwright test --output build --debug",
"test:headed": "playwright test --output build --headed",
"test:codegen": "playwright codegen https://xxx.xxx.com/ -o records.test.ts",
"test:codegen-json": "playwright codegen https://xxx.xxx.com/ --save-storage=storage/auth_1.json",
"test:api": "playwright test src/e2e-api/ --retries 0 --output build "
}
Then, in common line:
pnpm nx test e2e-tests --skip-nx-cache
or
pnpm nx test:debug e2e-tests --skip-nx-cache
or
pnpm nx test:headed e2e-tests --skip-nx-cache
e2e-tests is a e2e destination folder where the package.json is located
--skip-nx-cache - to skip nx cache output
This command line you can use in any place, for example in gitlab-ci.yaml

Rollup and eslint : How can I fix this error "TypeError: eslint is not a function" using eslint with rollup?

I'm trying to use rollup for the first time and I can't figure out why I get this error :
TypeError: eslint is not a function
I previously installed rollup (v1.1.0) then eslint npm install rollup-plugin-eslint (v5.0.0)
here is my rollup.config.js
import babel from 'rollup-plugin-babel';
import eslint from 'rollup-plugin-eslint';
export default {
input: 'src/main.js',
output: {
format: 'iife',
file: 'build/js/main.min.js',
name: 'main'
},
plugins: [
eslint({
exclude: [
'src/styles/**',
]
}),
babel({
exclude: 'node_modules/**',
}),
],
}
When I use ./node_modules/.bin/rollup -c I get this error TypeError: eslint is not a function. (NB : rollup is working fine with only babel)
However it works if I use npm run lint adding this code in package.json
"scripts": {
"lint": "eslint src/**"
}
What do I do wrong with the rollup configuration ?
Thanks for your help
Try changing:
- import eslint from 'rollup-plugin-eslint';
+ import { eslint } from 'rollup-plugin-eslint';
Release notes for v5.0.0

Resources