I'm kinda new to cucumber and selenium and I've been running into an issue with selenium webdriver where it doesn't connect or gets a "Error: ECONNREFUSED connect ECONNREFUSED "127.0.0.1:50546". I've tried both chromedriver and geckodriver for Firefox but still doesn't want to connect. I've been using the npm versions of each one as well as the downloaded ones. I've also tried simple synchronous code to get rid of the errors. I've also tried to specify the selenium-webdriver's port but that still doesn't work. Do I have to have the selenium stand-alone server? What am I missing here?
Gecko Driver Error: https://i.stack.imgur.com/oDtJB.png
Chrome Driver Error: https://i.stack.imgur.com/YhqhC.png
My .feature file:
Feature: Testing With Selenium
Scenario: Finding some cheese
Given I am on the Google search page
When I search for "Cheese!"
Then the page title should start with "cheese"
My step Definitions:
const {Given, When, Then, AfterAll} = require('#cucumber/cucumber');
const { Builder, By, Capabilities, Key } = require('selenium-webdriver');
const { expect } = require('chai');
const assert = require('assert');
//Driver and Browser setup
require('chromedriver');
const driver = new Builder().forBrowser('chrome').build();
function isItFriday(today) {
if(today == "Friday"){
return "TGIF";
}else{
return "Nope"
}
}
Given('today is {string}', function (givenDay) {
this.today = givenDay;
});
When('I ask whether it\'s Friday yet', function () {
this.actualAnswer = isItFriday(this.today);
});
Then('I should be told {string}', function (expectedAnswer) {
assert.strictEqual(this.actualAnswer, expectedAnswer);
});
Given('I am on the Google search page', {timeout: 60 * 1000}, async() => {
await driver.get('http://www.google.com');
});
When('I search for {string}', {timeout: 1000 * 1000}, async(searchTerm) => {
const element = await driver.findElement(By.name('q'));
element.sendKeys(searchTerm, Key.RETURN);
element.submit();
});
Then('the page title should start with {string}', function (string) {
const title = driver.getTitle();
const isTitleStartWithCheese = title.toLowerCase().lastIndexOf(`${searchTerm}`, 0) === 0;
expect(isTitleStartWithCheese).to.equal(true);
});
AfterAll(async () => {
await driver.quit();
});
My package.json file:
{
"name": "cucumberdemo",
"version": "1.0.0",
"description": "This is a demo project to understand the basics of Cucumber's BDD Testing Framework",
"main": "app.js",
"dependencies": {
"#cucumber/cucumber": "^8.0.0",
"chai": "^4.3.6",
"chromedriver": "^100.0.0",
"geckodriver": "^3.0.1",
"pactum": "^3.1.5",
"selenium-webdriver": "^4.1.1"
},
"scripts": {
"test": "cucumber-js"
},
"author": "Shahroz Noorani",
"license": "ISC"
}
Related
I am working on a nuxt project and I want to add it to Google Play, but it requires an apk output
so is there any solution to get the apk file from Nuxt?
I've already tried using android studio but it was unsuccessful
manifest.json:
{
"name": "my nuxt app",
"short_name": "my lovely nuxt app",
"description": "pwa to apk",
"icons": [
{
"src": "/logo.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/300.png",
"sizes": "384x384",
"type": "image/jpg"
},{
"src": "/512.jpg",
"sizes": "512x512",
"type": "image/jpg"
}
],
"start_url": "/?standalone=true",
"display": "standalone",
"background_color": "#222",
"theme_color": "#222",
"lang": "fa",
"prefer_related_applications": true
}
and I get this error when I want to install it:
for security your phone is set to block installation
TWA are a thing as you can read here: https://www.ateamsoftsolutions.com/what-are-pwa-and-twa/
Meanwhile, this is not the same as having an .apk which is something totally different from the Web platform as you can see here: https://fileinfo.com/extension/apk (none of the extensions are ones used on the Web)
This is a totally different bundle language and ecosystem. Hence, you cannot port a PWA into a Google Play app.
You'll need to learn ways to make a mobile app with either Capacitor (Quasar) can help or similar solutions.
Or use React Native, Flutter or even vanilla Kotlin (the latter being the closest one to the machine).
In addition to kissu's comment, I always use Nuxt.js for regular websites but Ionic/Vue with Capacitor for mobile apps, it works great, same ecosystem and a great UI components and CLI from Ionic. This is just a suggestion for something that works and it has a minimum learning curve.
after so many searches and thanks to #kissu for give me a hint about twa i found the solution:
1.first of all u need a service worker for your nuxt project and put it in the static folder
example:
/static/sw.js
and inside of sw.js:
const options = {"workboxURL":"https://cdn.jsdelivr.net/npm/workbox-cdn#5.1.4/workbox/workbox-sw.js","importScripts":[],"config":{"debug":false},"cacheOptions":{"cacheId":"online-actor-prod","directoryIndex":"/","revision":"c35hcbL1ctml"},"clientsClaim":true,"skipWaiting":true,"cleanupOutdatedCaches":true,"offlineAnalytics":false,"preCaching":[{"revision":"c35hcbL1ctml","url":"/"}],"runtimeCaching":[{"urlPattern":"/_nuxt/","handler":"CacheFirst","method":"GET","strategyPlugins":[]},{"urlPattern":"/","handler":"NetworkFirst","method":"GET","strategyPlugins":[]}],"offlinePage":null,"pagesURLPattern":"/","offlineStrategy":"NetworkFirst"}
importScripts(...[options.workboxURL, ...options.importScripts])
initWorkbox(workbox, options)
workboxExtensions(workbox, options)
precacheAssets(workbox, options)
cachingExtensions(workbox, options)
runtimeCaching(workbox, options)
offlinePage(workbox, options)
routingExtensions(workbox, options)
function getProp(obj, prop) {
return prop.split('.').reduce((p, c) => p[c], obj)
}
function initWorkbox(workbox, options) {
if (options.config) {
// Set workbox config
workbox.setConfig(options.config)
}
if (options.cacheNames) {
// Set workbox cache names
workbox.core.setCacheNameDetails(options.cacheNames)
}
if (options.clientsClaim) {
// Start controlling any existing clients as soon as it activates
workbox.core.clientsClaim()
}
if (options.skipWaiting) {
workbox.core.skipWaiting()
}
if (options.cleanupOutdatedCaches) {
workbox.precaching.cleanupOutdatedCaches()
}
if (options.offlineAnalytics) {
// Enable offline Google Analytics tracking
workbox.googleAnalytics.initialize()
}
}
function precacheAssets(workbox, options) {
if (options.preCaching.length) {
workbox.precaching.precacheAndRoute(options.preCaching, options.cacheOptions)
}
}
function runtimeCaching(workbox, options) {
const requestInterceptor = {
requestWillFetch({ request }) {
if (request.cache === 'only-if-cached' && request.mode === 'no-cors') {
return new Request(request.url, { ...request, cache: 'default', mode: 'no-cors' })
}
return request
},
fetchDidFail(ctx) {
ctx.error.message =
'[workbox] Network request for ' + ctx.request.url + ' threw an error: ' + ctx.error.message
console.error(ctx.error, 'Details:', ctx)
},
handlerDidError(ctx) {
ctx.error.message =
`[workbox] Network handler threw an error: ` + ctx.error.message
console.error(ctx.error, 'Details:', ctx)
return null
}
}
for (const entry of options.runtimeCaching) {
const urlPattern = new RegExp(entry.urlPattern)
const method = entry.method || 'GET'
const plugins = (entry.strategyPlugins || [])
.map(p => new (getProp(workbox, p.use))(...p.config))
plugins.unshift(requestInterceptor)
const strategyOptions = { ...entry.strategyOptions, plugins }
const strategy = new workbox.strategies[entry.handler](strategyOptions)
workbox.routing.registerRoute(urlPattern, strategy, method)
}
}
function offlinePage(workbox, options) {
if (options.offlinePage) {
// Register router handler for offlinePage
workbox.routing.registerRoute(new RegExp(options.pagesURLPattern), ({ request, event }) => {
const strategy = new workbox.strategies[options.offlineStrategy]
return strategy
.handle({ request, event })
.catch(() => caches.match(options.offlinePage))
})
}
}
function workboxExtensions(workbox, options) {
}
function cachingExtensions(workbox, options) {
}
function routingExtensions(workbox, options) {
}
2.you also need a manifest , for that put this code in your nuxt.config.js:
export default{
pwa: {
manifest: {
name: 'example name',
short_name: 'example',
lang: 'fa',
theme_color: '#222',
background_color: '#222',
start_url: `/`,
prefer_related_applications: true,
},
icon: {
fileName: 'logo.png'
},
},
}
3.now everything is ready to create your apk, now you can search for pwa to apk in google And use sites that offer these services:
ive already tried these sites and all working well:
gonative.io
or
pwabuilder.com
Trying to deploy a smart contract using Hardhat but getting configuration error.
Here is the complete error details
Error HH9: Error while loading Hardhat's configuration.
You probably tried to import the "hardhat" module from your config or a file imported from it.
This is not possible, as Hardhat can't be initialized while its config is being defined.
All the plug-ins seem to be have been installed correctly.
deploy.js
const hre = require("hardhat");
async function main() {
const TestContract = await hre.ethers.getContractFactory("TestContract");
const superInstance = await TestContract.deploy("TestContractHAT", "SMC");
await superInstance.deployed();
console.log("contract was deployed to:", superInstance.address());
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
package.json
{
"name": "Test",
"version": "1.0.0",
"description": "This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, a sample script that deploys that contract, and an example of a task implementation, which simply lists the available accounts.",
"main": "hardhat.config.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.5",
"#nomiclabs/hardhat-waffle": "^2.0.3",
"chai": "^4.3.6",
"ethereum-waffle": "^3.4.4",
"ethers": "^5.6.2"
},
"dependencies": {
"dotenv": "^16.0.0",
"hardhat": "^2.9.3"
}
}
Hardhat.config
const { ethers } = require("hardhat");
require('#nomiclabs/hardhat-waffle');
require("#nomiclabs/hardhat-ethers");
require('#openzeppelin/hardhat-upgrades');
require("dotenv").config();
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.2",
networks: {
mumbai: {
url: process.env.MUMBAI_URL,
account: process.env.PRIVATE_KEY
}
}
};
Any pointers are helpful. Thanks
As the error states, you are importing hardhat module in your hardhat configuration.
You probably tried to import the "hardhat" module from your config or a file imported from it. This is not possible, as Hardhat can't be initialized while its config is being defined.
Remove the line
const { ethers } = require("hardhat");
and the error should disappear
Just remove
const { ethers } = require("hardhat");
or
const { hardhatArguments } = require("hardhat");
or any other that requires hardhat
I am trying to integrate Jest and Puppeteer on Ubuntu. I have followed carefully this tutorial Using with puppeteer but I get this error when running my first test:
# npm test
[...]
FAIL ./test.js
● Test suite failed to run
TypeError: TestEnvironment is not a constructor
at node_modules/jest-runner/build/run_test.js:88:25
Here is how I setup the environment of my project:
~# mkdir jest-lab
~# cd jest-lab/
~/jest-lab# npm init -y
~/jest-lab# npm install --save-dev jest-puppeteer puppeteer jest
Then I copied and pasted the files from the tutorial Using with puppeteer.
I had to customize a bit the file setup.js to add the option "{args: ['--no-sandbox']}".
Here are all my project files:
jest.config.js
module.exports = {
globalSetup: './setup.js',
globalTeardown: './teardown.js',
testEnvironment: './puppeteer_environment.js',
};
package.json:
{
"name": "jest-lab",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^23.6.0",
"jest-puppeteer": "^3.7.0",
"puppeteer": "^1.11.0"
},
"jest": {
"verbose": true
}
}
puppeteer_environment.js:
// puppeteer_environment.js
const NodeEnvironment = require('jest-environment-node');
const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');
const os = require('os');
const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
class PuppeteerEnvironment extends NodeEnvironment {
constructor(config) {
super(config);
}
async setup() {
await super.setup();
// get the wsEndpoint
const wsEndpoint = fs.readFileSync(path.join(DIR, 'wsEndpoint'), 'utf8');
if (!wsEndpoint) {
throw new Error('wsEndpoint not found');
}
// connect to puppeteer
this.global.__BROWSER__ = await puppeteer.connect({
browserWSEndpoint: wsEndpoint,
});
}
async teardown() {
await super.teardown();
}
runScript(script) {
return super.runScript(script);
}
}
setup.js (customized to run chrome with --no-sandbox):
// setup.js
const puppeteer = require('puppeteer');
const mkdirp = require('mkdirp');
const path = require('path');
const fs = require('fs');
const os = require('os');
const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
module.exports = async function() {
const browser = await puppeteer.launch({args: ['--no-sandbox']});
// store the browser instance so we can teardown it later
// this global is only available in the teardown but not in TestEnvironments
global.__BROWSER_GLOBAL__ = browser;
// use the file system to expose the wsEndpoint for TestEnvironments
mkdirp.sync(DIR);
fs.writeFileSync(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint());
};
teardown.js:
// teardown.js
const os = require('os');
const rimraf = require('rimraf');
const path = require('path');
const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
module.exports = async function() {
// close the browser instance
await global.__BROWSER_GLOBAL__.close();
// clean-up the wsEndpoint file
rimraf.sync(DIR);
};
And finally here is test file test.js:
// test.js
const timeout = 5000;
describe(
'/ (Home Page)',
() => {
let page;
beforeAll(async () => {
page = await global.__BROWSER__.newPage();
await page.goto('https://google.com');
}, timeout);
it('should load without error', async () => {
const text = await page.evaluate(() => document.body.textContent);
expect(text).toContain('google');
});
},
timeout,
);
Add the following at the end of "puppeteer_environment.js"
module.exports = PuppeteerEnvironment;
I am a beginner and want to integrate front-end (angular js) with blockchain.
I have successfully compiled and deployed smart contract using Truffle.
Can I deploy the smart contract without using truffle i.e manual route.
I have searched many blogs but couldn't find a better source for this question. If you have a better source, please help me out
I have created the plan contract deployer using nodeJS. Please find below code.
Step 1: Install the nodeJS and NPM in your computer.
Step 2: Create "deployer" folder and add package.json in same folder
Step 3: Create "contracts" & "compiled" folder under "deployer" folder
Step 4: created deployer.js file in "deployer" folder.
Step 5: Run $npm install command
Step 6: Keep your smart contract ".sol" file in "contracts" folder.
Step 7: Run $node deployer.js command to deploy contract on local Ganache client (truffle). If you have other client or blockchain node. Please update rpc url in "deployer.js" file. OR install Ganache RPC client, you will find truffle site.
Files:
package.json:
{
"name": "deployer",
"version": "1.0.0",
"description": "Test deployer",
"main": "deployer.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Mahesh Patil",
"license": "ISC",
"dependencies": {
"async": "^2.6.0",
"body-parser": "1.15.2",
"express": "4.14.0",
"request": "2.79.0",
"solc": "0.4.8",
"web3": "0.18.2"
}
}
==========
deployer.js:
var Web3 = require("web3");
// Replace the blockchain node url, I am installed Ganache client very easy for testing
var web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545/"));
var fs = require('fs');
var solc = require('solc');
var async = require('async');
var cDir = fs.readdirSync("./contracts");
console.log(cDir);
var contracts = cDir.reduce(function (acc, file) {
acc[file] = fs.readFileSync("./contracts/" + file, { encoding: "utf8" });
return acc;
}, {});
var output = solc.compile({ sources: contracts }, 1);
if (output.errors) {
throw output.errors;
};
var owner = web3.eth.coinbase;
web3.eth.defaultAccount = owner;
var contracts = [];
web3.personal.unlockAccount(owner, "", 120000, function (err, success) {
var all = [];
Object.keys(output.contracts).forEach(function (name) {
var contract = output.contracts[name];
contract.interface = JSON.parse(contract.interface);
deployContract(contract, name).then(res => {
console.log(name, " Address: ", res);
})
});
});
function deployContract(contract, fileName) {
return new Promise((resolve, reject) => {
web3.eth.contract(contract.interface).new({
data: "0x" + contract.bytecode,
gas: 900000, // If you get gas issue please change this value according error
// privateFor: [],
from: owner,
}, function (err, myContract) {
if (err) {
console.log(err);
reject(err);
}
if (!err) {
if (!myContract.address) {
console.log(fileName + " : " + myContract.transactionHash); // The hash of the transaction, which deploys the contract
} else {
contract.address = myContract.address;
fs.writeFileSync("./compiled/" + fileName + ".json", JSON.stringify(contract, null, 4));
//cb(null, myContract.address); // the contract address
resolve(myContract.address);
}
}
});
});
}
While not ideal, you could technically use the Remix online IDE (http://remix.ethereum.org/) if you have Metamask installed.
I'm trying to build a functional testing system to verify our web site is behaving correctly for our users. I have cobbled together a bunch of Node.js modules and helpers in an attempt to get a framework that provides simple, concise tests without a heap of nested function callbacks and I believe promises can provide that, so my package.json file looks like this:
"dependencies": {
"chai-as-promised": "^4.3.0",
"grunt": "^0.4.5",
"grunt-webdriver": "^0.4.8"
}
My Gruntfile.js looks like this:
module.exports = function(grunt) {
grunt.initConfig({
webdriver: { // for use with webdriver.io
options: {
desiredCapabilities: {
browserName: 'phantomjs' // No Xvfb required
}
},
chrome: {
tests: ['chrome/*.js'],
options: {
desiredCapabilities: {
browserName: 'chrome'
}
}
},
},
});
grunt.loadNpmTasks('grunt-webdriver');
grunt.registerTask('default', ['webdriver']);
};
And finally my test case in chrome/login.js looks like this:
'use strict';
var chai = require('chai'),
chaiAsPromised = require('chai-as-promised'),
assert;
chaiAsPromised.transferPromiseness = browser.transferPromiseness;
chai.use(chaiAsPromised);
assert = chai.assert;
describe('login test', function () {
it('verifies user can log in', function(done) {
browser
.url('https://localhost/')
.setValue('#userauth_username','foo')
.setValue('#userauth_password',"password")
.submitForm('#form_users_login')
.then(function(){
browser.getText('#auth-user-id', function(err, value){
console.log(value);
});
assert.becomes(browser.getText('#auth-user-id'), 'foo');
})//.call(done);
});
});
When I run grunt webdriver:chrome on the command line, I see it start up Chrome and log into the website. The 'auth-user-id' span is correctly displaying the user's id after logging in but for some reason browser.getText() is not returning it and the test is therefore failing. I have tried adding a .pause(100) after the .submitForm() to give me time to interact with the page in Chrome so I know it is a problem in the test case.
What am I doing wrong?
This seems to be the best and most succinct way of doing what I want. I'm not sure I need chai-as-promised yet but maybe I'll move the login function to an included file and use chai-as-promised to assert that the promised login has occurred before entering the tests.
'use strict';
var chai = require('chai'),
chaiAsPromised = require('chai-as-promised'),
assert,
expect;
chaiAsPromised.transferPromiseness = browser.transferPromiseness;
chai.use(chaiAsPromised);
assert = chai.assert;
expect = chai.expect;
describe('login test', function () {
it('verifies user can log in', function(done) {
browser
.url('https://localhost/')
.setValue('#userauth_username','foo')
.setValue('#userauth_password',"password")
.submitForm('#form_users_login')
.waitForExist('#auth-user-id')
.getText('#auth-user-id')
.then(function(text){
//console.log('Username: ' + text);
assert.equal(text, 'foo');
})
.saveScreenshot('out.png')
.call(done)
});
it('should not display logincontrols after login', function(done){
browser
.isVisible('#logincontrols')
.then(function(bool){
expect(bool).to.be.false;
})
.call(done)
});
it('should display loggedin section after login', function(done){
browser
.isVisible('#loggedin')
.then(function(bool){
expect(bool).to.be.true;
})
.call(done)
});
});
and for completeness, this is what I see on the output:
# grunt webdriver:chrome
Running "webdriver:chrome" (webdriver) task
login test
✓ verifies user can log in (7691ms)
✓ should not display logincontrols after login (70ms)
✓ should display loggedin section after login (58ms)
3 passing (8s)
Done, without errors.