React-Scripts and Jest - No tests found on running npm test - javascript

I am testing reducers and storage.
I read the jest tutorial-react manual and it's a little different from mine, but I also found information that "react-scripts test" should also work
package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"dependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^13.5.0",
"classnames": "^2.3.1",
"faker": "^4.1.0",
"jest": "^27.4.7",
"miragejs": "^0.1.43",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"redux": "^4.1.2",
"seedrandom": "^3.0.5",
"web-vitals": "^2.1.3"
},
"devDependencies": {
"jest-watch-typeahead": "^0.6.5",
"prettier": "^2.5.1"
}
Commands
npm test
npm test --config jest.config.js
npm test --setupFile ./src/setupTests.js
npm test --setupFiles ./src/setupTests.js
Output
Active Filters: filename .\\src\\setupTests.js/
› Press c to clear filters.
Watch Usage
› Press a to run all tests.
› Press f to run only failed tests.
› Press o to only run tests related to changed files.
› Press q to quit watch mode.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press Enter to trigger a test run.
On pressing "a",
No tests found, exiting with code 0
Watch Usage: Press w to show more.
./jest.config.js
// Sync object
/** #type {import('#jest/types').Config.InitialOptions} */
const config = {
setupFiles: ['./src/setupTests.js'],
verbose: true,
};
module.exports = config;
./src/setupTests.js
import '#testing-library/jest-dom/extend-expect';
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});

This is what the Jest documentation says about how it finds test files:
By default it looks for .js, .jsx, .ts and .tsx files inside of __tests__ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js.
Since the setupTests.js filename does not meet this criteria, Jest does not recognize it as a test file. If you rename the file to end with .test.js or move it into a __tests__ folder, Jest should be able to find it and run the test. If you need to keep the filename as is, this default behavior can be changed by setting testRegex in jest.config.js (read more about this setting here).
The setupFiles property in jest.config.js is used for setting up the environment before the tests actually run. The documentation for that setting can be found here, but it doesn't appear to be necessary to do any setup for this case based code you provided.

Related

In Playwright, Cucumber feature files not being recognised from index.ts

In my Playwright test, I am trying to run a cucumber feature using npm run cucumber --profile dev, however no scenarios are being picked up:
Here is my index.ts file:
const common = `./src/features/**/*.feature \
--require-module ts-node/register \
--require ./src/step-definitions/**/**/*.ts \
-f json:./reports/report.json \
--format progress-bar `;
const dev = `${common} --tags '#dev'`;
const smoke = `${common} --tags '#smoke'`;
const regression = `${common} --tags '#regression'`;
export { dev, smoke, regression }
And here is my folder structure as that may be useful:
Also, my home-page.feature file:
Feature: As a user I expect to be able to navigate to the home page
#dev
#regression
Scenario: As a user I expect to be able to see contacts
Given I am on the 'home' page
Then the 'contacts header' should contain the text 'Contacts'
And my package.json:
{
"name": "personalised-offers-platform-e2e-pw",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"transpile": "rimraf dist && babel --extensions .ts --out-dir dist src",
"cucumber": "npm run transpile && cucumber-js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.18.9",
"#babel/preset-env": "^7.18.9",
"#babel/preset-typescript": "^7.18.6",
"#cucumber/cucumber": "^8.5.0",
"#playwright/test": "^1.23.4",
"playwright": "^1.23.4",
"ts-node": "^10.9.1",
"typescript": "^4.7.4"
}
}
I have tried running just npm run cucumber to see if the tags were the issue, but it gives the same output as above.
Originally, I thought the problem was with the common paths in my index.ts, as the feature wasn't being picked up, but they look OK to me now.
Can someone please explain what I'm doing wrong, & how I can fix it?
I can provide further code to help shed some light on the issue.
Try with "cucumber" option -p or --profile:
npm run transpile && cucumber-js -p

Code Coverage Sonar Qube for my React Javascript

The following is what I have for Coverage for my React JavaScript application. I am getting coverage locally with running npm test, but not reported in SonarQube. Can someone help me with what I am missing?
Gradle
// gradle sonar plugin configuration
apply plugin: 'org.sonarqube'
sonarqube {
properties {
property "sonar.projectName", "${project_name}-${version}"
property "sonar.projectKey", "${project_name}-$version}"
property "sonar.sources", "src/main/java/com/company/app,src/main/webapapp/appName/src"
property "sonar.exclusions", "src/main/webapp/appName/src/assests/**"
// Where to find tests file, also src
property "sonar.tests", "src/main/java/com/company/app,src/main/webapp/appName/src"
// But we get specific here
// We do not need to exclude it in sonar.sources because it is automatically taken care of
property "sonar.test.inclusions", "src/**/*.spec.js,src/**/*.spec.jsx,src/**/*.test.js,src**/*.test.jsx"
// Now specify path of lcov and test log
property "sonar.javascript.lcov.reportPaths", "src/main/webapp/appName/coverage/lcov.info"
//property "sonar.testExecutionReportPaths", "src/main/webapp/appName/coverage-final.json // does not work
sonar-project.properties
# Source
sonar.sources=src
# Where to find tests file, also src
sonar.tests=src
# But we get specific here
# We do not need to exclude it in sonar.sources because it is automatically taken care of
sonar.test.inclusions=src/**/*.spec.js,src/**/*.spec.jsx,src/**/*.test.js
,src/**/*.test.jsx
#sonar.testExecutionReportPaths=coverage/jest/testlog.xml
package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest --coverage",
"eject": "react-scripts eject"
},
"jest": {
"transform":{
"^.+\\.[t|j]sx?$": "babel-jest"
},
"collectCoverage": true,
"testResultsProcessor":"jest-sonar-reporter"
},
"homepage": "./",
"devDependencies": {
"jest": "^24.9.0",
"jest-junit-reporter: "^1.1.0"
},
...... removed for brevity
The jest-sonar-reporter package is old and hasn't been updated in 4 years. It has issues with paths not working as intended and failing to be reported.
I have updated the plugin and republished it under #casualbot/jest-sonar-reporter to fix this functionality as well as add other features for the community.
Ex:
package.json
{
...,
"jest": {
"rootDir": ".",
"testResultsProcessor": "#casualbot/jest-sonar-reporter"
},
"#casualbot/jest-sonar-reporter": {
"suiteName": "jest tests",
"outputDirectory": "coverage",
"outputName": "jest-report.xml",
"uniqueOutputName": "false",
"classNameTemplate": "{classname}-{title}",
"titleTemplate": "{classname}-{title}",
"ancestorSeparator": " › ",
"usePathForSuiteName": "true",
"relativePaths": "true"
}
}
Disclosure: I am the developer of the plugin.

husky pre-commit hook not working after adding it to package.json

I am working on a project and I want that every time I try to commit a new change, my tests are run and based on that it is decided whether the commit would happen. For this to happen I researched and found I can use husky's pre-commit hook.
I first installed husky in my project with
npm i husky --save-dev
which installed "husky": "^6.0.0" in my package.json.
Then I followed the tutorial and added the following object in package.json
"husky": {
"hooks": {
"applypatch-msg": "echo \"[Husky] applypatch-msg\"",
"pre-applypatch": "echo \"[Husky] pre-applypatch\"",
"post-applypatch": "echo \"[Husky] post-applypatch\"",
"pre-commit": "echo \"[Husky] pre-commit\""
}
}
As you can see, running git commit -m "some message!" should echo bunch of stuff which would mean that husky's pre-commit hook is working but instead nothing of the sort gets echoed. Now I have just no clue why is that not working. If it had worked I would have went on to add script in pre-commit hook to run my tests.
Here is the package.json file by the way:
{
"name": "test app",
"version": "1.0.1",
"description": "test app",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": nodemon index.js",
"test": "find ./plugins -name '*test.js' | xargs mocha -R spec"
},
"dependencies": {
"#hapi/boom": "^9.0.0",
"#hapi/glue": "^7.0.0",
"#hapi/good": "^9.0.0",
"#hapi/good-console": "^9.0.0",
"#hapi/good-squeeze": "^6.0.0",
"#hapi/hapi": "^19.1.1",
"#hapi/joi": "^17.1.1",
"axios": "^0.19.2",
"babel-eslint": "^10.1.0",
"base-64": "0.1.0",
"confit": "2.3.0",
"hapi-auth-jwt2": "^8.8.1",
"hapi-mongodb": "^9.0.0",
"jws": "4.0.0",
"mongodb": "^3.5.7",
"pad-left": "2.1.0",
"pino": "^5.16.0",
"query-string": "^6.13.1",
"redis": "^2.8.0",
"selectn": "^1.1.2",
"superagent": "3.8.2",
"utf8": "^3.0.0",
"uuid": "^3.4.0",
},
"devDependencies": {
"chai": "^4.1.2",
"chai-datetime": "^1.6.0",
"chai-http": "^4.0.0",
"husky": "^6.0.0",
"mocha": "^5.1.1",
"nodemon": "^2.0.4",
"proxyquire": "^2.0.1",
"sinon": "^5.0.10",
"sinon-test": "^2.2.0"
},
"husky": {
"hooks": {
"applypatch-msg": "echo \"[Husky] applypatch-msg\"",
"pre-applypatch": "echo \"[Husky] pre-applypatch\"",
"post-applypatch": "echo \"[Husky] post-applypatch\"",
"pre-commit": "echo \"[Husky] pre-commit\""
}
}
}
This is a bit old but maybe my solution will help someone.
It didn't work for me either to use this technique. The cleanest I found is
add script to package json:
"prepare": ""chmod ug+x ./installHooks.sh && ./installHooks.sh""
with installHooks.sh containing:
#!/bin/zsh
FILE=.husky
if test -d "$FILE"; then
echo "$FILE folder already exists, deleting it before new husky installation";
rm -rf "./$FILE"
# else echo "$FILE doesn't exist yet";
fi
cd ../ && husky install ./sub-project/.husky
cd sub-project && npx husky add .husky/pre-commit 'cd sub-project && npm test'
chmod ug+x ./.husky/*
echo "hooks correctly installed. you may find them in `.husky/pre-commit`"
echo "they will be triggered each time you commit"
Explanation:
The prepare script will be ran automatically when running npm install or can be ran with npm run prepare
It will change the mode of installHooks.sh to executable then run it.
installHooks will check if the .husky folder already exists, delete it if it's the case, then install husky (note that going up one folder then down in sub-project is because my git repo contains several sub projects and I want to install this in the front-end one, here called sub-project. husky requires that you install it from the root so this is a workaround). Then adding pre-commit hook (npm test) Finally make husky hooks executable with chmod
Let me know if you have questions. I'm just starting writing scripts so this might not be the optimal way of doing this but it works

Stop Jest from running tests on TS files and only on JS files

I can't get Jest, using the command npm test in my program to stop running tests on my TS files. I only want to run them on JS files.
PASS Views/Shared/Global.unit.test.js (14.83s)
FAIL Views/Shared/Global.unit.test.ts
I've got this in my package.json file:
{
"devDependencies": {
...,
"#types/jest": "^24.0.11",
"jest": "^24.7.1"
},
"scripts": {
"test": "jest"
}
}
I have written the tests in typescript and only want the tests to run the js. I've looked everywhere, but all I find are ways to add support for TS testing. I want it to only run on my .js files.
Anyone had this issue or know a fix?
After several hours of searching and messing with Jest documentation and settings, I finally found how to pick only the files you want Jest to look for. Add the "jest" field to the package.json file settings:
{
"devDependencies": {
...,
"#types/jest": "^24.0.11",
"jest": "^24.7.1"
},
"scripts": {
"test": "jest"
},
"jest": {
"testMatch": [
"**/?(*.)+(spec|test).[j]s?(x)"
]
}
}
This needs to be added to your package.json file. This is in the Jest Docs. In the regex above you need to change the .[jt]s just .[j]s, removing the "t".
or in jest.config.js
module.exports = {
...
testMatch: ["**/?(*.)+(spec|test).js"],
...
};

Using environment variables in React application

Our JavaScript resource just quit, so I, knowing nothing about front-end development, need to get my UI stood up. I'm trying to use an environment variable in the javascript, and it seems like there are 100 different ways to do it.
All I know is this is a react/node app. I start it with npm run start. It needs an endpoint I've defined in my .bash_profile, XREFS_BACK_URL. I thought I could just use process.env.XREFS_BACK_URL, but apparently that has to be defined in some file? I don't know what file or where it should be located.
Sorry to be so clueless - this just landed in my lap and I have to get it up quickly!
Update:
I created a .env file in the root directory. It's one line:
REACT_APP_XREFS_BACK_URL=http://localhost:8080
In my code, I try to use it like so:
var endpoint = process.env.REACT_APP_XREFS_BACK_URL;
console.log("endpoint is " + endpoint);
But the console shows that endpoint is UNDEFINED.
My package.json is here:
{
"name": "bulletin-board",
"version": "0.0.1",
"private": true,
"devDependencies": {
"babel-jest": "^22.4.1",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"jest": "^22.4.2",
"react-scripts": "0.2.1",
"react-test-renderer": "^16.2.0",
"webpack": "^4.6.0"
},
"dependencies": {
"font-awesome": "^4.7.0",
"match-sorter": "^2.2.1",
"namor": "^1.0.1",
"npm": "^6.0.0",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"react-draggable": "^2.2.0",
"react-table": "^6.8.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "jest"
},
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"moduleFileExtensions": [
"js",
"json",
"jsx"
],
"moduleNameMapper": {
"^.*[.](jpg|JPG|gif|GIF|png|PNG|less|LESS|css|CSS)$": "EmptyModule"
},
"preprocessorIgnorePatterns": [
"/node_modules/"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/EmptyModule.js"
]
},
"eslintConfig": {
"extends": "./node_modules/react-scripts/config/eslint.js"
}
}
Your app was made with create-react-app. Here are the docs for adding / referencing environment variables: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-custom-environment-variables
Create a file in the root folder called .env with the contents:
REACT_APP_XREFS_BACK_URL=put_whatever_here
Then access this variable in your JavaScript via:
process.env.REACT_APP_XREFS_BACK_URL
Dont sure, if it actual for you, CNDyson, but I think it might be helpful for newers like me:
npm install --save dotenv
create .env file in the root directory
declare there REACT_APP_**VARIABLE_NAME** = dont forget about REACT_APP
use it like this: process.env.REACT_APP_**VARIABLE_NAME**
Highly recommend to explore these links:
https://create-react-app.dev/docs/adding-custom-environment-variables/ -official documentaion
https://www.npmjs.com/package/dotenv - dotenv
The problem is that usually you want to access the environments variables present on the server that host your application.
With the described solution you will never be able to do docker run --env FOO="value of foo" my-org/my-app
then access FOO in the app like process.env["FOO"].
create-react-app bundle the environment variables that are defined when you run yarn build.
If you want, for example, access the environment variables defined in the docker container check out: react-envs
At first create a file named env.local beside package.json
and try to secure environment variables REACT_APP_YOUR ENV FILE NAME
now set the secured name to your firebase file and push it
as simple as that

Categories