Running tests with flags from chrome cypress - testing

I have some test cases that use webcam and our test enviroment needs for using webcam to have set flag in chrome --unsafely-treat-insecure-origin-as-secure
How can I for some test sets have this set in chrome with cypress?
Thanks

You can pass flags to the chrome browser in Cypress by writing a Cypress plugin as seen in the official documentation here: https://docs.cypress.io/api/plugins/browser-launch-api.html#Usage.
Navigate to your cypress/plugins directory and add the following code
module.exports = (on, config) => {
on('before:browser:launch', (browser = {}, launchOptions) => {
// `args` is an array of all the arguments that will
// be passed to browsers when it launches
if (browser.name === 'chrome') {
launchOptions.args.push('--unsafely-treat-insecure-origin-as-secure');
}
// whatever you return here becomes the launchOptions
return launchOptions;
});
};

Related

How do we use expect in WebdriverIO as a standalone script?

WebdriverIO has a sample of using it in a script:
https://webdriver.io/docs/gettingstarted#run-in-a-script
const { remote } = require('webdriverio');
;(async () => {
const browser = await remote({
capabilities: {
browserName: 'chrome'
}
})
await browser.url('https://webdriver.io')
const apiLink = await browser.$('=API')
await apiLink.click()
await browser.saveScreenshot('./screenshot.png')
await browser.deleteSession()
})()
However, there is no mentioning of how we can use expect, such as expect(elementFoo).toHaveText("Hello World") How can we have expect (and have one of mocha, jasmine, or cucumber like when we set up a webdriverio project using
npx wdio ./path/to/new/project
or is it already possible to use expect without using one of those three modules?)
Also, if we used npx wdio ./path/to/new/project to create a whole project, the expect(elementFoo).toHaveText("Hello World") knows how to wait a few seconds to finally say that it doesn't contain the text, which I am not sure if pure mocha, jasmine, or cucumber has that feature too.

Set up Cypress IO to work with dotenv on Quasar Framework

I'm using Quasar framework and just after I've added quasar-dotenv package I realized that e2e tests not working.
Uncaught TypeError: fs.readFileSync is not a function
This error originated from your test code, not from Cypress.
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
Cypress could not associate this error to any specific test.
We dynamically generated a new test to display this failure.
Check your console for the stack trace or click this message to see where it originated from.
at Object.config (http://localhost:8080/__cypress/tests?p=test/cypress/integration/home/init.spec.js-312:141291:34)
at Object.746.eslint (http://localhost:8080/__cypress/tests?p=test/cypress/integration/home/init.spec.js-312:150393:36)
at o (http://localhost:8080/__cypress/tests?p=test/cypress/integration/home/init.spec.js-312:1:265)
at http://localhost:8080/__cypress/tests?p=test/cypress/integration/home/init.spec.js-312:1:316
at Object.747.../../../../quasar.conf.js (http://localhost:8080/__cypress/tests?p=test/cypress/integration/home/init.spec.js-312:150535:35)
at o (http://localhost:8080/__cypress/tests?p=test/cypress/integration/home/init.spec.js-312:1:265)
at r (http://localhost:8080/__cypress/tests?p=test/cypress/integration/home/init.spec.js-312:1:431)
at http://localhost:8080/__cypress/tests?p=test/cypress/integration/home/init.spec.js-312:1:460
I've tried to set up the Cypress environment by adding the test/cypress/plugins/cypress.env.json file with some data, as well as changing the test/cypress/plugins/index.js file in the same folder, by following this documentation as it was suggested here:
const env = require('quasar-dotenv').config()
module.exports = (on, config) => {
// config.env.API_URL = 'http://example.com' // not working
config.env = env
// Chrome:: Hack for shaking AUT. Cypress Issue: https://github.com/cypress-io/cypress/issues/1620
on('before:browser:launch', (browser = {}, args) => {
if (browser.name === 'chrome') {
args.push('--disable-blink-features=RootLayerScrolling');
return args;
}
return true;
});
return config
};
MacOS Catalina
Cypress v3.5.0
Chrome v77
I don't know the answer because I am unfamiliar with quasar-dotenv. Have you tried the official quasar dotenv app extension? https://github.com/quasarframework/app-extension-dotenv or, alternatively, another official app extension, but less opinionated than dotenv wrappers: https://github.com/quasarframework/app-extension-qenv

Interaction between restartBrowserBetweenTests with onPrepare()

I want each of my tests to run on clean browser (Firefox) so i use restartBrowserBetweenTests:true option. Because i use non-Angular demo app, in onPrepare() function i use browser.waitForAngularEnabled(false). It's works fine, when i run a single spec, but when i run 2 specs, i have error.
Angular could not be found on the page. If this is not an Angular application, you may need to turn off waiting for Angular.
How can i solve this? And in addition, how onPrepare works in this case - every time when browser starts or one time before all specs?
Here is my conf.js
const screenshotReporter = require('./screenshotCustomReporter')
exports.config = {
capabilities: {
browserName: 'firefox'
},
restartBrowserBetweenTests: true,
framework: 'jasmine',
directConnect: true,
baseUrl: URL,
specs: ['path/**/*Spec.js'],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 30000,
includeStackTrace: true
},
onPrepare: () => {
require("#babel/register");
jasmine.getEnv().addReporter(screenshotReporter)
browser.waitForAngularEnabled(false)
}
}
You can recreate this issue using the following simple project:
conf.js
exports.config = {
framework: 'jasmine',
specs: ['./app.1.js', './app.2.js'],
seleniumAddress: 'http://localhost:4444/wd/hub',
restartBrowserBetweenTests:true,
onPrepare:function(){
browser.waitForAngularEnabled(false);
},
}
app.1.js
describe('second test', () => {
it('should check is displayed successfully', () => {
browser.driver.get("https://stackoverflow.com");
browser.driver.sleep(5000);
expect(element(by.linkText('Ask Question')).isDisplayed()).toBe(true);
});
});
app.2.js
describe('first test', () => {
it('should check is displayed successfully', () => {
browser.driver.get("https://stackoverflow.com");
browser.driver.sleep(5000);
expect(element(by.linkText('Ask Question')).isDisplayed()).toBe(true);
});
});
OnPrepare is defined for all settings need to be executed for suite. It means it
is always one time operation irrespective of number of spec files.
One concept you need to understand is that whenever the new instance of
firefox browser is launched then WebdriverJs initialize the instance of webdriver.
and global object browser in protractor also gets initialized.
In your case First spec file start firefox browser, OnPrepare function is executed afterwards and
default setting of protractor is overriden by WaitForAngularEnabled.But when you run second spec file,
again firefox browser is launched with fresh instance of webdriver and protractor browser which expect
angular application and in that case test case gets failed.
The solution for this problem is to use before function in spec file
describe('first test', () => {
before(() => {
browser.waitForAngularEnabled(false);
});
it('should check is displayed successfully', () => {
browser.driver.get("https://stackoverflow.com");
browser.driver.sleep(5000);
expect(element(by.linkText('Ask Question')).isDisplayed()).toBe(true);
});
});
Note : If you are using restartBrowserBetweenTests: true then you will have to use beforeEach() function for waitForAngularEnabled because every time fresh instance of webdriver will be created.

In Nightwatch, `.url()` blocks assertions for too long

It appears that using browser.url() (http://nightwatchjs.org/api/#url) to navigate causes the WebDriver client to wait until the page is fully loaded - however I have assertions I want to make before that point.
"Shows splash screen for a few seconds": function(client) {
client
.url(client.testURL)
// at this point, the splash has already come and gone, so
// this next command times out
.waitForElementVisible('#splash img', 10000)
.waitForElementNotVisible('#splash', 10000);
},
Is this possible? I think my only other option is to disable the splash in a test scenario.
I'm running these tests on Firefox v45.
You can do this by setting Firefox profile preferences as shown in below
https://github.com/nightwatchjs/nightwatch/issues/748
The preference you need to set is webdriver.load.strategy to be unstable. But this means that waiting for page to load is now all your business
var FirefoxProfile = require('firefox-profile');
function setProfile(browser, profile, callback) {
profile.encoded(function (encodedProfile) {
browser.options.desiredCapabilities['firefox_profile'] = encodedProfile;
callback();
});
}
function setFirefoxProfile(browser, done) {
var profile = new FirefoxProfile();
profile.setPreference('webdriver.load.strategy', 'unstable');
setProfile(browser, profile, done);
}
// and in my test module
before: function (browser, done) {
setFirefoxProfile(browser, done);
}

How to integrate sauce-connect-launcher on webdriver.io wdio.conf.js file

I read this http://webdriver.io/guide/testrunner/cloudservices.html, but not find how launch the tunnel inside the wdio.conf.js and how integrate.
Update:
Now webdriver.io latest version have documentation to integrate the cloud testing services.
See to more:
http://webdriver.io/guide/testrunner/cloudservices.html
Fomerly to integrate the sauce-connect-launcher you need the wdio.conf.js file, and inside the file configure the sauce-connect-launcher to launch the tunnel, example wdio.conf.js file:
var sauceConnectLauncher = require('sauce-connect-launcher');
global.sauceConnectProcess = null;
exports.config = {
//
// ==================
// Specify Test Files
// ==================
// Define which test specs should run. The pattern is relative to the directory
// from which `wdio` was called. Notice that, if you are calling `wdio` from an
// NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
// directory is where your package.json resides, so `wdio` will be called from there.
//
user: 'the_pianist2',
key: '27dde83a-1cf7-450d-8c88-857c4d3cde43',
specs: [
//command line
//'spec/**/*.js' wdio wdio.conf.js
//grunt
'./www-test/e2e/spec/*.js'
],
// Patterns to exclude.
exclude: [
// 'path/to/excluded/files'
],
//
// ============
// Capabilities
// ============
// Define your capabilities here. WebdriverIO can run multiple capabilties at the same
// time. Depending on the number of capabilities, WebdriverIO launches several test
// sessions. Within your capabilities you can overwrite the spec and exclude option in
// order to group specific specs to a specific capability.
//
// If you have trouble getting all important capabilities together, check out the
// Sauce Labs platform configurator - a great tool to configure your capabilities:
// https://docs.saucelabs.com/reference/platforms-configurator
//
capabilities: [{
browserName: 'chrome'
},
{
browserName: 'firefox'
}
],
//
// ===================
// Test Configurations
// ===================
// Define all options that are relevant for the WebdriverIO instance here
//
// Level of logging verbosity.
//logLevel: 'result',
//
// Enables colors for log output.
coloredLogs: true,
//
// Saves a screenshot to a given path if a command fails.
screenshotPath: './errorShots/',
//
// Set a base URL in order to shorten url command calls. If your url parameter starts
// with "/", the base url gets prepended.
//desarrollo
baseUrl: 'http://localhost:3001',
//produccion
//baseUrl: 'http://www.example.com',
//
// Default timeout for all waitForXXX commands.
waitforTimeout: 20000,
//
// Initialize the browser instance with a WebdriverIO plugin. The object should have the
// plugin name as key and the desired plugin options as property. Make sure you have
// the plugin installed before running any tests. The following plugins are currently
// available:
// WebdriverCSS: https://github.com/webdriverio/webdrivercss
// WebdriverRTC: https://github.com/webdriverio/webdriverrtc
// Browserevent: https://github.com/webdriverio/browserevent
// plugins: {
// webdrivercss: {
// screenshotRoot: 'my-shots',
// failedComparisonsRoot: 'diffs',
// misMatchTolerance: 0.05,
// screenWidth: [320,480,640,1024]
// },
// webdriverrtc: {},
// browserevent: {}
// },
//
// Framework you want to run your specs with.
// The following are supported: mocha, jasmine and cucumber
// see also: http://webdriver.io/guide/testrunner/frameworks.html
//
// Make sure you have the node package for the specific framework installed before running
// any tests. If not please install the following package:
// Mocha: `$ npm install mocha`
// Jasmine: `$ npm install jasmine`
// Cucumber: `$ npm install cucumber`
framework: 'jasmine',
//
// Test reporter for stdout.
// The following are supported: dot (default), spec and xunit
// see also: http://webdriver.io/guide/testrunner/reporters.html
reporter: 'spec',
reporterOptions: {
//
// If you are using the "xunit" reporter you should define the directory where
// WebdriverIO should save all unit reports.
outputDir: './'
},
//
// Options to be passed to Jasmine.
jasmineNodeOpts: {
//
// Jasmine default timeout
defaultTimeoutInterval: 20000,
//
// The Jasmine framework allows it to intercept each assertion in order to log the state of the application
// or website depending on the result. For example it is pretty handy to take a screenshot everytime
// an assertion fails.
expectationResultHandler: function(passed, assertion) {
}
},
//
// =====
// Hooks
// =====
// Run functions before or after the test. If one of them returns with a promise, WebdriverIO
// will wait until that promise got resolved to continue.
//
// Gets executed before all workers get launched.
onPrepare: function() {
return new Promise(function(resolve, reject) {
sauceConnectLauncher({
username: 'the_pianist2',
accessKey: '27dde83a-1cf7-450d-8c88-857c4d3cde43',
}, function (err, sauceConnectProcess) {
if (err) {
return reject(err);
}
console.log('conexion realizada');
global.sauceConnectProcess = sauceConnectProcess
resolve();
});
});
},
//
// Gets executed before test execution begins. At this point you will have access to all global
// variables like `browser`. It is the perfect place to define custom commands.
before: function() {
// do something
},
//
// Gets executed after all tests are done. You still have access to all global variables from
// the test.
after: function(failures, pid) {
// do something
},
//
// Gets executed after all workers got shut down and the process is about to exit. It is not
// possible to defer the end of the process using a promise.
onComplete: function() {
console.log('Test completado');
global.sauceConnectProcess.close(function () {
console.log("Closed Sauce Connect process");
return true;
});
}};
In the hook 'onPrepare' the script to connect tunnel is launch and the inside Promise is very important because wait the callback of connection and run the next steps after finish onPrepare functions:
https://github.com/webdriverio/webdriverio/issues/1062
After that the test is launching on the server saucelabs.