Cypress: Can't use --env variables from command line in test file - javascript

In my Cypress setup I have the following values (plus others) in my cypress.json file:
{
"PREPROD": {
"url": "https://preprod.com",
"username": "admin",
"password": "admin"
},
"PROD": {
"url": "https://prod.com",
"username": "admin",
"password": "admin"
}
}
I have my test file located in cypress/integration/test.js
Based on what environment I want to run my test, I'd like to use the values relevant to that environment in my test file
I've tried running like this:
npx cypress run --env environment="PREPROD" --spec "cypress/integration/test.js"
This returns an error saying that environment is not defined.
In my test file I have the following to use the variable from command line:
Cypress.config().environment.username
How do I go about using the variables that I define in command line?
I've tried reading the documentation here but its not working for me: Cypress Documentation

According to the documentation, you can access the environment variable like this:
Cypress.env('environment')
If you want to get the options depending on this you could do as follow:
const CypressConfiguration = require('cypress.json')
const environment = Cypress.env('environment') || 'PREPROD'
const options = CypressConfiguration[environment]
One other approach would be to use the config-file option:
cypress.prod.json
{
"url": "https://prod.com",
"username": "admin",
"password": "admin"
}
cypress.preprod.json
{
"url": "https://preprod.com",
"username": "admin",
"password": "admin"
}
Then:
npx cypress run --config-file cypress.prod.json --spec "cypress/integration/test.js"

Related

Typescript issues with multiple projects in the same VSCode workspace

I work with a VSCode workspace that holds various projects, often containing a Nuxt.js application, that has its own tsconfig.json. I recently added an Nx monorepo to the mix and it looks like my typings are not found by IntelliSense anymore.
My workspace looks like the following, with 3 projects so far.
my-project
--tsconfig.json
my-other-project
--tsconfig.json
my-monorepo
--tsconfig.base.json
apps/my-app
--tsconfig.json
--tsconfig.spec.json
I now get errors like this if I open a file in my-project for instance, but if I open the project alone in another VSCode instance, the error is gone.
const { $axios } = context;
Property '$axios' does not exist on type 'Context'.ts(2339)
The definiton is here but it seems like it's not found in a multi-project setup.
my-project/tsconfig.json
"types": [
"#nuxt/types",
"#types/node",
"#nuxtjs/i18n",
"#types/jest",
"#testing-library/vue",
"#testing-library/jest-dom",
"#pinia/nuxt",
"#nuxtjs/axios" <- The definition
],
I'm using Takeover Mode along with the Volar extension, maybe that could also explain why I run into these kinds of problems.
workspace.code-workspace
{
"folders": [
{
"name": "my-project",
"path": "my-project"
},
{
"name": "my-other-project",
"path": "my-other-project"
},
{
"name": "my-monorepo",
"path": "my-monorepo"
}
],
"settings": {}
}

Cannot get #vercel/ncc working throws Module not found error

I have been trying to get the following tutorial working for building custom github actions https://docs.github.com/en/actions/creating-actions/creating-a-javascript-action. The article states that if you don't want to check in your node_modules folder to use #vercel/ncc package to compile your code into a single file. I have tried the NCC sample here https://github.com/vercel/ncc/tree/main/examples/hello-world but I get the same error no matter what I do. The error I get is this:
Error: Cannot find module 'C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\index.js'
Require stack:
- C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc\cli.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at resolve (node:internal/modules/cjs/helpers:108:19)
at runCmd (C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc/cli.js.cache.js:1:52001)
at Object.819 (C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc/cli.js.cache.js:1:48838)
at __webpack_require__ (C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc/cli.js.cache.js:1:59074)
at C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc/cli.js.cache.js:1:59286
at C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc/cli.js.cache.js:1:59347
at Object.<anonymous> (C:\Projects\github-runner-test\.github\actions\read-deploy-instructions\node_modules\#vercel\ncc\dist\ncc\cli.js:8:28)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Projects\\github-runner-test\\.github\\actions\\read-deploy-instructions\\node_modules\\#vercel\\ncc\\dist\\ncc\\cli.js'
]
}
I am running latest Node on Windows 10 with latest GIT and cannot get this to work at all. I have tried bash, powershell, moved directories around and nothing seems to work. Below is my project structure:
My package.json looks like this:
{
"name": "read-deploy-instructions",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "ncc build index.js -o /dist"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#actions/core": "^1.9.0",
"#actions/github": "^5.0.3"
},
"devDependencies": {
"#vercel/ncc": "latest"
}
}
My index.js looks like this:
import core from '#actions/core';
import github from '#actions/github';
try {
// `who-to-greet` input defined in action metadata file
const nameToGreet = core.getInput('who-to-greet');
console.log(`Hello ${nameToGreet}!`);
const time = (new Date()).toTimeString();
core.setOutput("time", time);
// Get the JSON webhook payload for the event that triggered the workflow
const payload = JSON.stringify(github.context.payload, undefined, 2)
console.log(`The event payload: ${payload}`);
} catch (error) {
core.setFailed(error.message);
}
If I run the command:
npm run build
I get the error shown above. I have seen multiple people posting it doesn't work with similar errors but no resolution. Does anyone have any ideas?
Thanks in advance,
OK after many a wasted hour I realized the file I was trying to target was named incorrectly. I was telling the NCC commands to look for "index.js" but had mistakenly named it "index,js". After renaming the file the NCC commands worked successfully and as expected.

GitHub Action [cypress CI integration ]: How to set env variables before running cypress run command

I am writing workflows for my repository, and I want to run test cases whenever there is a code push.
Here is the code snippet from .yml file:
- name: Run cypress test
with:
env: true
env:
username: ${{secrets.CYPRESS_USERNAME}}
password: ${{secrets.CYPRESS_PASSWORD}}
run: npm run cy:test --env fileConfig=production, username=$username, password=$password
continue-on-error: false
Snippet from JSON :
{
"env": {
"userId": "1",
"environment": "production",
"baseUrl": " base URL"
}
}
So, I want to pass the username and password along with the configfile in the cypress run command so that they can be set as the env variable because I am using username and password for my login test module.
With the above code i am getting error :
The workflow is not valid. .github/workflows/main.yml (Line: 43, Col: 9): Unexpected value 'run' .github/workflows/main.yml (Line: 36, Col: 9): Required property is missing: uses
Thanks :)
First, you need to add the env variables as empty strings on cypress.json:
{
"env": {
"userId": "1",
"environment": "production",
"baseUrl": "base URL",
"username": "",
"password": ""
}
}
In main.yml file, you need to add the CYPRESS_ prefix to the variables:
env:
CYPRESS_username: ${{secrets.CYPRESS_USERNAME}}
CYPRESS_password: ${{secrets.CYPRESS_PASSWORD}}
Also, you should use the setup that can be found on cypress docs (https://docs.cypress.io/guides/continuous-integration/github-actions#Basic-Setup), example:
name: Cypress Tests
on: [push]
jobs:
cypress-run:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout#v2
# Install NPM dependencies, cache them correctly
# and run all Cypress tests
- name: Cypress run
uses: cypress-io/github-action#v2
with:
build: npm run build
start: npm start
env:
CYPRESS_username: ${{secrets.CYPRESS_USERNAME}}
CYPRESS_password: ${{secrets.CYPRESS_PASSWORD}}
You should also read this article: https://glebbahmutov.com/blog/keep-passwords-secret-in-e2e-tests/

"The term '/node.exe' is not recognized as the name of a cmdlet, function, script file, or operable program"

I'm attempting to make a CLI with Node.js following the tutorial on Twilio and after doing npm link I get this error when using the command. I read an old overflow post which said to add node to my environment variables, which I have.
Here's the error:
& : The term '/node.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\thedi\AppData\Roaming\npm\create-project.ps1:15 char:5
+ & "/node$exe" "$basedir/node_modules/#thedigs/create-project/bin/c ...
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (/node.exe:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
And here's my current code:
// bin/create-project
#!/usr/bin/env/node
require = require('esm')(module /*, options */);
require('../src/cli').cli(process.argv);
// src/cli.js
export function cli(args) {
console.log(args);
}
// package.json
{
"name": "#thedigs/create-project",
"version": "1.0.0",
"description": "A CLI to bootstrap my new projects, whatever that means.",
"main": "src/index.js",
"scripts": {
"start": "nodemon ."
},
"publishConfig": {
"access": "public"
},
"bin": {
"#thedigs/create-project": "bin/create-project",
"create-project": "bin/create-project"
},
"keywords": [
"cli",
"create-project"
],
"author": "thedigs",
"license": "ISC",
"dependencies": {
"#types/node": "^14.14.31",
"esm": "^3.2.25",
"nodemon": "^2.0.7"
}
}
My best guess is the tutorial is behind versions, hopefully one of you can sort this out for me. Thanks!
Environment Variables
I was also looking for the answer but after comparing this code and my code suddenly realized that the path #!/usr/bin/env/node given to bin/create-project is completely wrong.
In my case, I have given it as #! /user/bin/env node but it has to be usr instead of using user.
In this case, it has to be...
File: bin/create-project
#! /usr/bin/env node
require = require('esm')(module /*, options */);
require('../src/cli').cli(process.argv);
Those spaces are a must when it comes to path.
For reference: first line is a so-called shebang.
And why to use env here and not call node directly, is summarized here in another SE post.
Short: env acts as a proxy to find your desired interpreter, in your case node on the target system, even if it is maybe found in the users ~ home dir or something...

How do I execute different Testcases with different structure through NodeJS and Mocha

How do I execute different Testcases with different structure through NodeJS and Mocha.
Moving forward I intend to integrate Selenium + NodeJS + Mocha
I have just started to explore NodeJS with Mocha and need some help.
Installed node.js:
C:\Users\AtechM_03>node -v
v6.11.2
Installed npm:
C:\Users\AtechM_03>npm -v
3.10.10
Configured nodeclipse as per this link and my Project structure looks like:
Installed Mocha at the default location (through command-line) as per this link.
C:\Users\AtechM_03>npm install -g mocha
C:\Users\AtechM_03\AppData\Roaming\npm\mocha -> C:\Users\AtechM_03\AppData\Roaming\npnode_modules\mocha\bin\mocha
C:\Users\AtechM_03\AppData\Roaming\npm\_mocha -> C:\Users\AtechM_03\AppData\Roaming\n\node_modules\mocha\bin\_mocha
C:\Users\AtechM_03\AppData\Roaming\npm
`-- mocha#3.5.3
Followed this link to write a program in NodeJS integrating Mocha.
Created a directory named test with in NodeProject space.
Within test folder created a file named test.js
Executed npm init to interactively create a package.json file.
C:\Users\AtechM_03>cd C:\Users\AtechM_03\LearnAutmation\NodeProject
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (NodeProject) test
version: (1.0.0) 1.0.0
description: test123
entry point: (index.js) test.js
test command: (mocha) mocha
git repository:
keywords:
author: debanjan
license: (ISC)
About to write to C:\Users\AtechM_03\LearnAutmation\NodeProject\package.json:
{
"name": "test",
"version": "1.0.0",
"description": "test123",
"main": "test.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjan",
"license": "ISC"
}
Is this ok? (yes)
C:\Users\AtechM_03\LearnAutmation\NodeProject>
package.json got generated within the Project Scope i.e. under C:\Users\AtechM_03\LearnAutmation\NodeProject as follows:
{
"name": "test",
"version": "1.0.0",
"description": "test123",
"main": "test.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjan",
"license": "ISC"
}
Added code to test.js as follows:
// Require the built in 'assertion' library
var assert = require('assert');
// Create a group of tests about Arrays
describe('Array', function() {
// Within our Array group, Create a group of tests for indexOf
describe('#indexOf()', function() {
// A string explanation of what we're testing
it('should return -1 when the value is not present', function(){
// Our actual test: -1 should equal indexOf(...)
assert.equal(-1, [1,2,3].indexOf(4));
});
});
//Create a test suite (group) called Math
describe('Math', function() {
// Test One: A string explanation of what we're testing
it('should test if 3*3 = 9', function(){
// Our actual test: 3*3 SHOULD EQUAL 9
assert.equal(9, 3*3);
});
// Test Two: A string explanation of what we're testing
it('should test if (3-4)*8 = -8', function(){
// Our actual test: (3-4)*8 SHOULD EQUAL -8
assert.equal(-8, (3-4)*8);
});
});
});
Executed npm test from project space which runs successfully:
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm test
> temperature#1.0.0 test C:\Users\AtechM_03\LearnAutmation\NodeProject
> mocha
Array
#indexOf()
v should return -1 when the value is not present
Math
v should test if 3*3 = 9
v should test if (3-4)*8 = -8
3 passing (18ms)
Followed this link to write a second program in NodeJS integrating Mocha.
Created a separate directory named temperature with in NodeProject space.
In the temperature directory created a file named app.js and a folder name test
Within the test folder, created a file named test.js
Moved the previous package.json to a sub-directory and executed npm init to interactively create a new package.json file again.
C:\Users\AtechM_03>cd C:\Users\AtechM_03\LearnAutmation\NodeProject
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (NodeProject) temperature
version: (1.0.0) 1.0.0
description: temp
entry point: (index.js) app.js
test command: (mocha) mocha
git repository:
keywords:
author: debanjanb
license: (ISC)
About to write to C:\Users\AtechM_03\LearnAutmation\NodeProject\package.json:
{
"name": "temperature",
"version": "1.0.0",
"description": "temp",
"main": "app.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjanb",
"license": "ISC"
}
Is this ok? (yes)
New package.json gets created as follows:
{
"name": "temperature",
"version": "1.0.0",
"description": "temp",
"main": "app.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjanb",
"license": "ISC"
}
The current temperature Testcase looks like:
Tried to execute this second program through npm test from the Project space but it still executes the first program as follows:
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm test
> temperature#1.0.0 test C:\Users\AtechM_03\LearnAutmation\NodeProject
> mocha
Array
#indexOf()
v should return -1 when the value is not present
Math
v should test if 3*3 = 9
v should test if (3-4)*8 = -8
3 passing (18ms)
Question :
I know my second program app.js is incomplete and executing it will show error (e.g. 0 passing (20ms)) but my app.js is not getting invoked at all.
Can someone please guide/suggest me what I am doing wrong here?
Any suggestion/guide/pointer will be helpful.
Update:
As of now my current code for app.js is incomplete and contains the following code:
cToF = function(celsius) {
if(!Number.isInteger(celsius)) return undefined;
return celsius * 9 / 5 + 32;
}
fToC = function(fahrenheit) {
if(!Number.isInteger(fahrenheit)) return undefined;
return (fahrenheit - 32) * 5 / 9;
}
As per this website I am following I expect an error as 0 passing (20ms)
You've got quite the long description but the thing I extracted from it is that you have essentially a structure like this:
NodeProject
├── temperature
│   └── test
└── test
Then you go into NodeProject and run Mocha. By default Mocha will look only for test in the same directory where it is invoked. So it won't look for temperature/test. If you want Mocha to run the tests in temperature/test you have to tell Mocha explicitly. For instance, this would work:
mocha test temperature/test
I'll address a common misconception here because I often see people make the mistake: merely using the --recursive flag is not enough. If you use this flag, then after Mocha has identified directories in which to find tests, it will look in them recursively. However, it does not change how Mocha identifies directories in which to find tests. Specifically, if you use mocha --recursive, it will still only look in test, and it will look in subdirectories of test. This won't make it look in temperature/test. If you do have subdirectories in test and temperature/test, you could do:
mocha --recursive test temperature/test

Categories