Cucumber testing example is not running - cucumber

I have setup a working nightwatch environment and now want to use cucumber for testing. I have followed this guide: https://www.youtube.com/watch?v=Jdlsv0CQ2CY&t=22s. No matter what I try I cannot get the test to work, I get this as output:
> cucumberpractice#1.0.0 test /Users/kieran/Documents/cucumberPractice
> cucumber-js --require cucumber.conf.js --require step-definitions --format node_modules/cucumber-pretty
Feature: Hacker News Search
Scenario: Searching Hacker News
Given I open Hacker News's home page
? undefined
Then the title is "Hacker News"
? undefined
And the Hacker News search form exists
? undefined
Warnings:
1) Scenario: Searching Hacker News # features/hackernews.feature:3
? Given I open Hacker News's home page
Undefined. Implement with the following snippet:
Given('I open Hacker News\'s home page', function () {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
? Then the title is "Hacker News"
Undefined. Implement with the following snippet:
Then('the title is {string}', function (string) {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
? And the Hacker News search form exists
Undefined. Implement with the following snippet:
Then('the Hacker News search form exists', function () {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
1 scenario (1 undefined)
3 steps (3 undefined)
0m00.000s
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! cucumberpractice#1.0.0 test: `cucumber-js --require cucumber.conf.js --require step-definitions --format node_modules/cucumber-pretty`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cucumberpractice#1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/kieran/.npm/_logs/2019-09-13T20_22_09_135Z-debug.log
I have package.json, nightwatch.conf.js, cucumber.conf.js, hackernews.feature and hackernews.js files.
const { client } = require('nightwatch-api');
const { Given, Then } = require('cucumber');
Given(/^I open Hacker News's home page$/, () => {
return client
.url('https://news.ycombinator.com/')
.waitForElementVisible('body', 1000);
});
Then(/^the title is "([^"]*)"$/, title => {
return client.assert.title(title);
});
Then(/^the Hacker News search form exists$/, () => {
return client.assert.visible('input[name="q"]');
});
Feature: Hacker News Search
Scenario: Searching Hacker News
Given I open Hacker News's home page
Then the title is "Hacker News"
And the Hacker News search form exists
const chromedriver = require('chromedriver');
module.exports = {
"src_folders": ["tests"],
test_settings: {
default: {
webdriver: {
start_process: true,
server_path: chromedriver.path,
port: 4444,
cli_args: ['--port=4444']
},
desiredCapabilities: {
browserName: 'chrome'
}
}
}
};
{
"name": "cucumberpractice",
"version": "1.0.0",
"description": "Cucumber framework",
"main": "index.js",
"scripts": {
"test": "cucumber-js --require cucumber.conf.js --require step-definitions --format node_modules/cucumber-pretty"
},
"repository": {
"type": "git",
"url": "git+https://github.com/BinaryJava/nightwatch-testing.git"
},
"author": "Kieran Marriott",
"license": "ISC",
"bugs": {
"url": "https://github.com/BinaryJava/nightwatch-testing/issues"
},
"homepage": "https://github.com/BinaryJava/nightwatch-testing#readme",
"devDependencies": {
"chromedriver": "^76.0.1",
"nightwatch": "^1.2.2"
},
"dependencies": {
"cucumber": "^5.1.0",
"cucumber-pretty": "^1.5.2",
"nightwatch-api": "^2.3.0"
}
}
How do I fix this?

you might giving the path wrong for step definition file in your package.json file,
"scripts": {
"test": "cucumber-js --require cucumber.conf.js --require step-definitions --format node_modules/cucumber-pretty"
},
for example my, here is my code in package,json,
"scripts": {
"test": "cucumber-js --require cucumber.conf.js --require tests --format node_modules/cucumber-pretty"
},
"--require tests": here "test" is the location folder where my feature file and my step definition files are exist.

Instead of Scenario: Searching Hacker News
you have to put
Scenario Outline: Searching Hacker News
to add Examples

Related

TypeError: trying to use aws-elasticsearch-connector

I'm attempting to update a legacy elastic-search node app, using the the package aws-elasticsearch-connector
and for some reason I'm unable to get it to work at all, even the simplest provided example...
I installed the packages, exactly as shown...
> npm install --save aws-elasticsearch-connector #elastic/elasticsearch aws-sdk
This is the sample code...
const { Client } = require('#elastic/elasticsearch')
const AWS = require('aws-sdk')
const createAwsElasticsearchConnector = require('aws-elasticsearch-connector')
// (Optional) load profile credentials from file
AWS.config.update({
profile: 'myawsprofile'
})
const client = new Client({
...createAwsElasticsearchConnector(AWS.config),
node: 'https://my-elasticsearch-cluster.us-east-1.es.amazonaws.com'
})
When I attempt to run it with this...
> node .\index.js
I get this error...
class AmazonConnection extends Connection {
TypeError: Class extends value undefined is not a constructor or null
I have no idea how I'm supposed to fix this, since the error seems to be in the module itself, not my sample code.
Most of the examples of this error that I've seen, suggest that it's related to circular references, but that doesn't seem to be of any help to me.
I'm using node v16.14.0
This is my package.json...
{
"name": "test_es",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"#elastic/elasticsearch": "^8.0.0",
"aws-elasticsearch-connector": "^9.0.3",
"aws-sdk": "^2.1087.0"
}
}
I'm probably doing something wrong, or the package author may be assuming some additional knowledge that I just don't have.
Any suggestions would be greatly appreciated.
It seems version 8 of #elastic/elasticsearch is not compatible with aws-elasticsearch-connector.
Changing to version 7.17.0 seems to resolve this particular error.

typeORM No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command

I'm doing a course where we are using express-node postgres and react (with typescript) and typeORM. Everything has worked well so far, but I'm facing an issue with typeORM and I don't know what is going and why is this error happening
The Big Problem : So, the problem is that, I was doing the auth, and at some point we changed users schema in the DB so we had to make a migration, but, before migration, we did npm run typeorm schema:drop ,but when I tried, this happened with migration
This is the first command I used
npm run typeorm migration:generate -- --n create-users-table
This was the error
> new-typeorm-project#0.0.1 typeorm C:\Users\diego cifuentes\Desktop\Studying Backend\redit> ts-node ./node_modules/typeorm/cli.js "migration:generate" "create-users-table"
bin.js migration:generate
Generates a new migration file with sql needs to be executed to update
schema.
Opciones:
-h, --help Muestra ayuda [booleano] -c, --connection Name of the connection on which run a query.
[defecto: "default"] -n, --name Name of the migration class.
[cadena de caracteres] [requerido] -d, --dir Directory where migration should be created.
-p, --pretty Pretty-print generated SQL
[booleano] [defecto: false] -f, --config Name of the file with connection configuration.
[defecto: "ormconfig"] -o, --outputJs Generate a migration file on Javascript instead of
Typescript [booleano] [defecto: false] --dr, --dryrun Prints out the contents of the migration instead of
writing it to a file [booleano] [defecto: false] --ch, --check Verifies that the current database is up to date and that no migrations are needed. Otherwise exits with
code 1. [booleano] [defecto: false] -v, --version Muestra número de versión [booleano]
Falta argumento requerido: n
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! new-typeorm-project#0.0.1 typeorm: `ts-node ./node_modules/typeorm/cli.js "migration:generate" "create-users-table"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the new-typeorm-project#0.0.1 typeorm script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\diego cifuentes\AppData\Roaming\npm-cache\_logs\2021-05-11T15_29_02_081Z-debug.log
After hours trying to search for solution everywhere, I change the last command to this one
npx typeorm migration:generate -- --n create-users-table
And the error was different this time, looks like this
No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command
So, I said, ok, I'm getting closer to fixing this, but... After hours ( again ) looking for a new answer, I couldn't find anything, so, I'm getting to a point where I need to write this post in order to fix my problem. So now, let me show you my ormconfig, my package.json and the entity I want to migrate in my postgres DB.
package.json (the script typeorm is at the end)
{
"name": "new-typeorm-project",
"version": "0.0.1",
"description": "Awesome project developed with TypeORM.",
"devDependencies": {
"#types/bcrypt": "^5.0.0",
"#types/cookie": "^0.4.0",
"#types/cookie-parser": "^1.4.2",
"#types/express": "^4.17.11",
"#types/jsonwebtoken": "^8.5.1",
"#types/morgan": "^1.9.2",
"#types/node": "^15.0.2",
"morgan": "^1.10.0",
"nodemon": "^2.0.7",
"ts-node": "^9.1.1",
"typescript": "^4.2.4"
},
"dependencies": {
"bcrypt": "^5.0.1",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"cookie": "^0.4.1",
"cookie-parser": "^1.4.5",
"dotenv": "^9.0.1",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"pg": "^8.4.0",
"reflect-metadata": "^0.1.10",
"typeorm": "0.2.32"
},
"scripts": {
"start": "ts-node src/server.ts",
"dev": "nodemon --exec ts-node src/server.ts",
"typeorm": "ts-node ./node_modules/typeorm/cli.js"
}
}
ormconfing.json Quick note : I changed entities, migrations and subscribers to .js, because with .ts was always giving me error.
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "**",
"password": "**",
"database": "**",
"synchronize": true,
"logging": true,
"entities": ["src/entities/**/*.js"],
"migrations": ["src/migrations/**/*.js"],
"subscribers": ["src/subscribers/**/*.js"],
"cli": {
"entitiesDir": "src/entities",
"migrationsDir": "src/migrations",
"subscribersDir": "src/subscribers"
}
}
And last thing I want to show you, even though it might not be that important, this is the users schema
import {
Entity as TOEntity,
Column,
Index,
BeforeInsert,
OneToMany
} from "typeorm";
import bcrypt from "bcrypt";
import { IsEmail, Length } from "class-validator";
import { Exclude } from "class-transformer";
import Entity from "./Entity";
// import Post from "./Post";
#TOEntity("users")
export default class User extends Entity {
constructor(user: Partial<User>) {
super();
Object.assign(this, user);
}
#Index()
#IsEmail()
#Column({ unique: true })
email: string;
#Index()
#Length(3, 200)
#Column({ unique: true })
username: string;
#Exclude()
#Length(6, 200)
#Column()
password: string;
// #OneToMany(() => Post, post => post.user)
// posts: Post[];
#BeforeInsert()
async hashedPassword() {
this.password = await bcrypt.hash(this.password, 6);
}
}
End Goal: So, if you can help me with this, you will save my life. One last thing is that I tried to post my problems first in the Spanish website of stack overflow, but nobody could help me, so maybe here someone will, thanks for your time and take care!
Change your entities, migrations and subscribers into your dist directory.
e.g.:
entities: ["dist/entities/**/*{.js,.ts}"],
migrations: ["dist/migrations/**/*{.js,.ts}"],
subscribers: ["dist/subscribers/**/*{.js,.ts}"],
dist directory is the directory which gets created when you build the app. You can find your dist directory using tsconfig.json -> compilerOptions -> outDir.
Then build your app again using npm run build and try to generate the migrations.
For me the ormconfig.json's was like this,
"entities": [
"dist/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
],
Changing it to
"entities": [
"src/entity/**/*{.js,.ts}"
],
"migrations": [
"src/migration/**/*{.js,.ts}"
],
"subscribers": [
"src/subscriber/**/*{.js,.ts}"
],
generated the migration correctly.
And the package.json script is like this
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"
And the command used is
npm run typeorm migration:generate -- -n FileAddTemporaryDeletedFields -p --dr --ch
I've seen this error, and if I'm not mistaken it's because I was trying to create a bank that had already been created.
This command below deletes all tables:
yarn typeorm query "DROP SCHEMA public CASCADE; CREATE SCHEMA public; GRANT USAGE ON SCHEMA public to PUBLIC; GRANT CREATE ON SCHEMA public to PUBLIC; COMMENT ON SCHEMA public IS 'standard public schema';"
then:
yarn typeorm --migration:generate -n migration_name -d path/to/your/migrations/
ormconfig.json is deprecated in latest version as i know.
but anyway I'm gonna share my solution when i used old version.
when generate, typeorm first reads ormconfig.json and login into rdbms.
and compares between 'the actual schema of db' and
'schema file as ormconfig.json[entities]'
so, if the file (writen at 'entities' in ormconfig.json) is in dist folder.
you have to edit that .js file.(not .ts file in src folder)
but, if the 'entities' file is in src folder as ormconfig.json,
check if 'autosave' feature of vscode is on.
if you 'npm run start:dev'
It could be the case that the actual schema of db has been already modified
before you edit entities file.

Is there a way to pass the cypress.io baseUrl env var into my package.json run scripts?

I want to be able to pass the baseUrl from the cypress.json file into the scripts of the package.json file for my cypress test project. Is this possible?
I have been looking at the cypress documentation and stack overflow but I cannot find a solution that does not require adding another script to do something like "get-base-url": "type cypress.json | jq -r .baseUrl" and pass this script as an argument into the relevant "test" script (see below)
cypress.json file
{
"baseUrl": "http://localhost:3000/",
//other key-value pairs
}
}
package.json scripts section
{
//other settings
"scripts": {
//other scripts
"test": "start-server-and-test website:dev http://localhost:3000 cy:run",
},
//other settings
}
I anticipated there would be an equivalent to Cypress.config().baseUrl, to get the value of the baseUrl in the json file.
Resulting in something similar to the following (sudo-code, doesnt work)
{
//other settings
"scripts": {
//other scripts
"test": "start-server-and-test website:dev ${baseUrl} cy:run",
},
//other settings
}
NB: I have not posted on Stack Overflow before, so I apologise if I have not given enough info and/or missed something in the rules.
scripts capability is limited. You need a small script to receive baseUrl from cypress.json and pass it into the start-server-and-test package
Let's say we create a script called start-server-and-test.js with the following code and put it under the scripts directory
const cypressConfig = require('../cypress.json') // line 1
const startServerAndTest = require('start-server-and-test') // line 2
const [startScript, testScript] = process.argv.slice(2) // line 3
startServerAndTest({ // line 4
start: `npm ${startScript}`,
url: cypressConfig.baseUrl,
test: `npm ${testScript}`,
})
Here is how we use it in package.json
{
"scripts": {
"test": "node scripts/start-server-and-test.js website:dev cy:run",
},
}
Short explanation:
Line 1: read cypress.json and assign to cypressConfig which you can access baseUrl later by cypressConfig.baseUrl
Line 3: retrieve arguments in the command-line which are ['website:dev', 'cy:run']
Line 4: Run the package with corresponding parameters
Just wanted to elaborate on Hung Tran's solution above for 2021:
/* eslint-disable #typescript-eslint/no-var-requires */
require("dotenv").config();
const startServerAndTest = require("start-server-and-test");
const [startScript, testScript] = process.argv.slice(2);
startServerAndTest.startAndTest({
services: [{ start: `npm run ${startScript}`, url: process.env.CYPRESS_BASE_URL }],
test: `npm run ${testScript}`,
});

Nodejs app with npm start script

I'm very new to nodejs.
In my dockerized environment, I want to provide appdynamics support to nodejs apps. This mandates every app to require the following as the first line in their app.
require("appdynamics").profile({
controllerHostName: '<controller host name>',
controllerPort: <controller port number>,
controllerSslEnabled: false, // Set to true if controllerPort is SSL
accountName: '<AppDynamics_account_name>',
accountAccessKey: '<AppDynamics_account_key>', //required
applicationName: 'your_app_name',
tierName: 'choose_a_tier_name',
nodeName: 'choose_a_node_name',
});
I plan to do that by providing a wrapper called appdynamics.js around the app's entry file. Details:
I run a script in my nodejs docker image to replace the entry file name in the app's package.json with "appdynamics.js", where appdynamics.js has the above appdynamics related require statement.
Ex : {scripts { "start" : "node server.js" }} will be replaced with
{scripts { "start" : "node appdynamics.js"}}
Then, i "require" the "server.js" inside appdynamics.js.
Invoke npm start.
My only concern is this:
If the package.json had something like scripts { "start" : "coffee server.coffee" }, my script will replace it to { "start" : "coffee appdynamics.js" }. and then my script will invoke npm start, which will error out.
What is the best way to solve this?
This is a follow up question to Use "coffee" instead of "node" command in production
Write a wrapper called appdynamics.coffee
Compile this wrapper to .js
Replace server.js with appdynamics.js and server.coffee with appdynamics.coffee
After this operations
{
"scripts": {
"start": "node server.js"
}
}
will be
{
"scripts": {
"start": "node appdynamics.js"
}
}
and
{
"scripts": {
"start": "coffee server.coffee"
}
}
will be
{
"scripts": {
"start": "coffee appdynamics.coffee"
}
}

Display license on package install node

How to use npm scripts and a postinstall hook to display the license of an npm package. Right now I'm doing it with:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"postinstall": "cat ./MIT-license.txt"
},
on the package.json. But this fails on windows because, well, cat. I know that we can use type on windows to output the contents of a file over the console, but how to do that in an npm script (without failing cat on windows and type on unix/mac)?
If i understand correctly, you need a cross-platform mechanism for logging the contents of a file to the console. I think the easiest way to do this is via a custom Node script, since you know the user will have Node installed, whatever their operating system.
Just write a script like this:
// print-license.js
'use strict';
const fs = require('fs');
fs.readFile('./MIT-license.txt', 'utf8', (err, content) => {
console.log(content);
});
And then, in your package.json:
// package.json
"scripts": {
"postinstall": "node ./print-license.js"
},
Or, if you don't want a serparate script hanging around, this is just about short enough to do inline, like so:
// package.json
"scripts": {
"postinstall": "node -e \"require('fs').readFile('./MIT-license.txt', 'utf8', function(err, contents) { console.log(contents); });\""
},
Update
And now that I think about it, you might be better off with a reusable executable that would allow you to specify a file as a command line argument. That's also very simple:
// bin/printfile
#!/usr/bin/env node
'use strict';
const FILE = process.argv[2];
require('fs').readFile(FILE, 'utf8', (err, contents) => {
console.log(contents);
});
And add the following to your package.json:
// package.json
"bin": {
"printfile": "./bin/printfile"
},
"scripts": {
"postinstall": "printfile ./MIT-license.txt"
}

Resources