Is there a way to prevent Walk-Me from loading, when running Protractor tests? - jasmine

I am trying to run a handfull of end-to-end (E2E) tests using Protractor and Jasmine. I am using Chrome as my browser of taste; and when I run the tests in full-flesh mode (i.e. not headless), the tests all run successfully. However, when I run the tests in headless mode, I keep getting an error that says the element I'm trying to click was intercepted by another element. The tool that seems to be getting in the way is WalkMe https://www.walkme.com/. I have used the following code to determine when my desired element is present, visible, enabled, and clickable, but this does not seem to help.
let isDisplayed;
let isEnabled;
let isPresent;
let EC = protractor.ExpectedConditions;
isDisplayed = await element(by.id(<locator-of-type-id>)).isDisplayed();
isEnabled = await element(by.id(<locator-of-type-id>)).isEnabled();
isPresent = await element(by.id(<locator-of-type-id>)).isPresent();
let elm = await element(by.id(<locator-of-type-id>));
await browser.wait(EC.elementToBeClickable(elm), 5000);
Thank you in advance for your time and effort.

Yes! You can't imagine how much I struggled with WalkMe... Here is the solution
// disable walkme for the session
await browser.executeScript(`
if (!!window.WalkMeAPI) {
window._walkMe.removeWalkMe();
(function() {
try {
var envName = "none";
document.cookie = "walkme_custom_user_settings_env=" + envName + ";path=/;";
window.localStorage.setItem("walkme_custom_user_settings_env", envName);
} catch(e) {
alert(e);
}
})();
}
`);
So basically you're disabling the integration, though by injecting a code to the browser's console
Though it's been a while since I used it last time, so hopefully not much is changed in their API

Another quick way to stop WalkMe from bugging you is to mock out your browser request to url /walkme/i, or whatever url your WalkMe script is sending API to(which you can check in your browser devtool network tab).
Quick example by myself in Cypress here https://liunate.medium.com/disable-walkme-to-avoid-flaky-cypress-end-to-end-tests-aaf73e213aed I think Protractor or other e2e testing framework should be able to intercept the same.

Related

Tips on solving 'DevTools was disconnected from the page' and Electron Helper dies

I've a problem with Electron where the app goes blank. i.e. It becomes a white screen. If I open the dev tools it displays the following message.
In ActivityMonitor I can see the number of Electron Helper processes drops from 3 to 2 when this happens. Plus it seems I'm not the only person to come across it. e.g.
Facing "Devtools was disconnected from the page. Once page is reloaded, Devtools will automatically reconnect."
Electron dying without any information, what now?
But I've yet to find an answer that helps. In scenarios where Electron crashes are there any good approaches to identifying the problem?
For context I'm loading an sdk into Electron. Originally I was using browserify to package it which worked fine. But I want to move to the SDKs npm release. This version seems to have introduced the problem (though the code should be the same).
A good bit of time has passed since I originally posted this question. I'll answer it myself in case my mistake can assist anyone.
I never got a "solution" to the original problem. At a much later date I switched across to the npm release of the sdk and it worked.
But before that time I'd hit this issue again. Luckily, by then, I'd added a logger that also wrote console to file. With it I noticed that a JavaScript syntax error caused the crash. e.g. Missing closing bracket, etc.
I suspect that's what caused my original problem. But the Chrome dev tools do the worst thing by blanking the console rather than preserve it when the tools crash.
Code I used to setup a logger
/*global window */
const winston = require('winston');
const prettyMs = require('pretty-ms');
/**
* Proxy the standard 'console' object and redirect it toward a logger.
*/
class Logger {
constructor() {
// Retain a reference to the original console
this.originalConsole = window.console;
this.timers = new Map([]);
// Configure a logger
this.logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
})
),
transports: [
new winston.transports.File(
{
filename: `${require('electron').remote.app.getPath('userData')}/logs/downloader.log`, // Note: require('electron').remote is undefined when I include it in the normal imports
handleExceptions: true, // Log unhandled exceptions
maxsize: 1048576, // 10 MB
maxFiles: 10
}
)
]
});
const _this = this;
// Switch out the console with a proxied version
window.console = new Proxy(this.originalConsole, {
// Override the console functions
get(target, property) {
// Leverage the identical logger functions
if (['debug', 'info', 'warn', 'error'].includes(property)) return (...parameters) => {
_this.logger[property](parameters);
// Simple approach to logging to console. Initially considered
// using a custom logger. But this is much easier to implement.
// Downside is that the format differs but I can live with that
_this.originalConsole[property](...parameters);
}
// The log function differs in logger so map it to info
if ('log' === property) return (...parameters) => {
_this.logger.info(parameters);
_this.originalConsole.info(...parameters);
}
// Re-implement the time and timeEnd functions
if ('time' === property) return (label) => _this.timers.set(label, window.performance.now());
if ('timeEnd' === property) return (label) => {
const now = window.performance.now();
if (!_this.timers.has(label)) {
_this.logger.warn(`console.timeEnd('${label}') called without preceding console.time('${label}')! Or console.timeEnd('${label}') has been called more than once.`)
}
const timeTaken = prettyMs(now - _this.timers.get(label));
_this.timers.delete(label);
const message = `${label} ${timeTaken}`;
_this.logger.info(message);
_this.originalConsole.info(message);
}
// Any non-overriden functions are passed to console
return target[property];
}
});
}
}
/**
* Calling this function switches the window.console for a proxied version.
* The proxy allows us to redirect the call to a logger.
*/
function switchConsoleToLogger() { new Logger(); } // eslint-disable-line no-unused-vars
Then in index.html I load this script first
<script src="js/logger.js"></script>
<script>switchConsoleToLogger()</script>
I had installed Google Chrome version 79.0.3945.130 (64 bit). My app was going to crash every time when I was in debug mode. I try all the solutions I found on the web but no one was useful. I downgrade to all the previous version:
78.x Crashed
77.x Crashed
75.x Not Crashed
I had to re-install the version 75.0.3770.80 (64 bit). Problem has been solved. It can be a new versions of Chrome problem. I sent feedback to Chrome assistence.
My problem was that I was not loading a page such as index.html. Once I loaded problem went away.
parentWindow = new BrowserWindow({
title: 'parent'
});
parentWindow.loadURL(`file://${__dirname}/index.html`);
parentWindow.webContents.openDevTools();
The trick to debugging a crash like this, is to enable logging, which is apparently disabled by default. This is done by setting the environment variable ELECTRON_ENABLE_LOGGING=1, as mentioned in this GitHub issue.
With that enabled, you should see something along the lines of this in the console:
You can download Google Chrome Canary. I was facing this problem on Google Chrome where DevTools was crashing every time on the same spot. On Chrome Canary the debugger doesn't crash.
I also faced the exact same problem
I was trying to require sqlite3 module from renderer side
which was causing a problem but once i removed the request it was working just fine
const {app , BrowserWindow , ipcMain, ipcRenderer } = require('electron')
const { event } = require('jquery')
const sqlite3 = require('sqlite3').verbose(); // <<== problem
I think the best way to solve this (if your code is really really small) just try to remove functions and run it over and over again eventually you can narrow it down to the core problem
It is a really tedious , dumb and not a smart way of doing it , but hey it worked
I encountered this issue, and couldn't figure out why the the DevTool was constantly disconnecting. So on a whim I launched Firefox Developer edition and identified the cause as an undefined variable with a string length property.
if ( args.length > 1 ) {
$( this ).find( "option" ).each(function () {
$( $( this ).attr( "s-group" ) ).hide();
});
$( args ).show();
}
TL;DR Firefox Developer edition can identify these kinds of problems when Chrome's DevTool fails.
After reading the comments above it is clear to me that there is a problem at least in Chrome that consists of not showing any indication of what the fault comes from. In Firefox, the program works but with a long delay.
But, as Shane Gannon said, the origin of the problem is certainly not in a browser but it is in the code: in my case, I had opened a while loop without adding the corresponding incremental, which made the loop infinite. As in the example below:
var a = 0;
while (a < 10) {
...
a ++ // this is the part I was missing;
}
Once this was corrected, the problem disappeared.
I found that upgrading to
react 17.0.2
react-dom 17.0.2
react-scripts 4.0.3
but also as react-scripts start is being used to run electron maybe its just react scripts that needs updating.
Well I nearly went crazy but with electron the main problem I realized I commented out the code to fetch (index.html)
// and load the index.html of the app.
mainWindow.loadFile('index.html');
check this side and make sure you have included it. without this the page will go black or wont load. so check your index.js to see if there's something to load your index.html file :) feel free to mail : profnird#gmail.com if you need additional help
Downgrade from Electron 11 to Electron 8.2 worked for me in Angular 11 - Electron - Typeorm -sqlite3 app.
It is not a solution as such, but it is an assumption of why the problem.
In the angular 'ngOnInit' lifecycle I put too many 'for' and 'while' loops, one inside the other, after cleaning the code and making it more compact, the problem disappeared, I think maybe because it didn't finish the processes within a time limit I hope someone finds this comment helpful. :)
I have stumbled upon the similar problem, My approach is comment out some line that I just added to see if it works. And if that is the case, those problem is at those lines of code.
for(var i = 0;i<objLen; i+3 ){
input_data.push(jsonObj[i].reading2);
input_label.push(jsonObj[i].dateTime);
}
The console works fine after i change the code to like this.
for(var i = 0;i<objLen; i=i+space ){
input_data.push(jsonObj[i].reading2);
input_label.push(jsonObj[i].dateTime);
}
Open your google dev console (Ctrl + shift + i). Then press (fn + F1) or just F1, then scroll down and click on the Restore defaults and reload.

How to validate an element is gone using webdriverIO, Mocha and Chai

I'm working on some automated tests, using webdriverIO, Mocha and Chai. I keep running into the same problem when I want to verify if an element is deleted.
I'm working with a shoppingbasket where i delete an item and then verify that it is gone. It takes a while for the item to be gone though, so if I immediately go to the expect, the item is still there.
I have solved this by doing this:
browser.waitForExist(deletedProduct, 5000, true)
expect (boodschappenLijstPage.isProductPresent(SKU), 'the removed item was still there' ).to.equal(false)
The webdriverIO waitfor command waits for the product to dissapear, and after that the chai expect checks if it is gone.
The problem I have with this is that the expect will never fail. If the product is not properly deleted the waitfortimeout will throw an error before I get to the expect part, meaning that the expect part is only reached if the product is gone
I have read through the docs for chai, but I can't seem to find a way of doing this.
Can anyone show be a way of waiting for the product to be gone, without missing the expect (I don't want to use browser.pause for obvious reasons)
Refer this
webElement.waitForDisplayed({ reverse: true });
You can use try catch and basically wait for error. When element disappears from DOM selenium will throw NoSuchElementError and we can use it.
isNotPresent(element) {
try {
return !element.isVisible()
} catch (error) {
return true
}
}
// or wait for element to disappear from dom
waitForNotVisible(element) {
browser.waitUntil(() => {
try {
return !element.isVisible()
} catch (error) {
return true
}
})
}
If you're trying to validate that an element is gone, then using expect is the correct solution, but you should use the Webdriver-expect assertions instead of the chai expect assertions. While chai assertions check the state immediately, the WebdriverIO-expect assertions have the waitFor functionality built inside of it. Here is an example:
let deletedProduct = $(/* your xpath/CSS selector/*);
expect(deletedProduct).not.toBeDisplayed();
The difference between the assertion and using waitForDisplayed with the reverse flag is that some reporters, such as Allure, will report your test as broken when instead the test should be reported as failed. For example, when we ran tests and had the waitForDisplayed, all of our failing tests were marked in yellow. When we use expect, the tests are marked in red.
Here is the documentation for the WebdriverIO Expect matchers. They didn't document the .not method very clearly, but in my example you can see I added the .not before the toBeDisplayed call.
Again, this expect will wait for the timeout specified in the wdio.conf.js, just like the waitFors will.

mock StripeCheckout in Jasmine test

I am writing Jasmine tests for my Javascript application. A major time-sink has been testing my code which depends on StripeCheckout. Stripe does not want you to use it offline. I realized I should mock the service, but that has not been easy in Jasmine.
How can I mock "custom" (instead of "simple") usage of StripeCheckout?
I tried to use spies, like so,
var StripeCheckout = jasmine.createSpyObj('StripeCheckout', ['configure']);
But I think the created object needs to attach to the global object (window).
So, I can add an object to the global
object. This worked,
but it feels lame.
Another option could be to tell
Karma to load the
page over the network. This worked for me, but it seems lame to make
a network request for tests.
I'm not sure if you have figured this out yet but an easy way to do this would be to just create a simple mocked implementation for StripeCheckout. Something like this should work.
beforeEach(function() {
module(function($provide) {
$provide.factory('StripeCheckout', function() {
//your mocked custom implementation goes here
configure: function() {
//do something
}
}
}
inject(function($injector) {
StripeCheckoutMock = $injector.get('StripeCheckout');
}
)
This way you are not making a request in order to run your tests. The test will just use the mocked service that you have set up.

Suppress REST Logging Calls from Supertest

I have started using MEAN stack and currently writing REST unit tests using Super Test
I want to have a little bit more clarity in my log file so that I can easily see my successful and failed tests.
I wish to suppress the console output for the actual rest API call which I think are coming out of SuperTest.
This image shows the logs I want to suppress.
I think it's actually coming from expressjs/morgan. I've gotten around it by setting the env to test and disabling morgan for the test env.
In my test files:
process.env.NODE_ENV = 'test';
In app.js:
if(app.get('env') !== 'test') app.use(logger('dev'));
You can setup morgan to accept a skip function.
Then, you can, say, toggle an env variable on/off - or define skipping logic of your own to temporarily mute the logging.
app.use(
logger('dev', {
skip: function(req, res) {
return process.env.MUTE_LOGGER === 'on';
},
}),
);

Protractor with mocha and chai

I started using Protractor and the first thing I've tried to do is to use Mocha and Chai instead of Jasmine. Although now I'm not sure if that was a good idea.
first I needed to make Chai accessible from all the spec files, without having to import everytime, I found it's possible to do in protractor.conf file:
onPrepare: ->
global.chai = require 'chai'
chai.use require 'chai-string'
chai.use require 'chai-as-promised'
global.expect = chai.expect
now in a spec like this:
it "when clicked should sort ",->
headerColumns.get(0).click()
firstCellText = $$(".first-cell").getText()
secondCellText = $$(".second-cell").getText()
# this won't work
expect(firstCellText).eventually.be.above(secondCellText)
to make it work I could do:
# now this works
$$(".second-cell").getText().then (secondCellText)->
expect(firstCellText).eventually.be.above(secondCellText)
but that's ugly, and I don't want to wrap stuff inside of .then all the time. I'm thinking there should be a better way(?)
I was having the same problem. The issue for me was to add a longer timeout to mocha through the Protractor config.js.
This works because Protractor tests take considerably longer relative to other modules like supertest since an actual browser is being interacted with.
I added
mochaOpts: {
timeout: 5000
}
to my protractor config and the tests passed.
Either you need to mention timeout for the whole test suite using "this.timeout(1000);" just below the describe block, or you can change it for individual test cases by explicitly defining timeout for each "it" block.
example for describe block:
describe("test-suite",function () {
this.timeout(5000);
it("test-case",function () {
//test case code goes here
});
});
example for it block:
it("test-case",function () {
this.timeout("20000");
});
I found this question while I was trying to do the same thing in TypeScript, but the approach in the protractor.conf.js is identical.
Making chai available globally
It appears to achieve this you're right that it needs to be done in the on prepare. a fairly terse example is below. As I understand it this is needed because chai is of course not apart of mocha but some additional candy that we can use with mocha. Unlike jasmine where everything is bundled into the framework.
protractor.conf.js fragment
onPrepare: function() {
var chai = require('chai'); // chai
var chaiAsPromised = require("chai-as-promised"); // deal with promises from protractor
chai.use(chaiAsPromised); // add promise candy to the candy of chai
global.chai = chai; // expose chai globally
}
example spec
Once you've got chai and chai-as-promised setup globally you need to add a "little" boiler plate to your spec to expose expect which comes from chai.
example.e2e-spec.ts fragment
const expect = global['chai'].expect; // obviously TypeScript
it('will display its title', () => {
pageObject.navigateTo();
const title = element(by.css('app-root h1')).getText();
expect(title).to.eventually.contain('An awesome title');
});
Avoiding then
I can't tell what your $$ references are, but if you're using the protractor components browser and by etc. then things clean up a little bit.
The call const title = element(by.css('app-root h1')).getText(); seems to return a promise which jasmine seems to deal with out of the box while mocha+chai doesn't. That's where chai-as-promised comes in.
using our additional syntax candy expect(title).to.eventually.contain('An awesome title'); resolves the promise quite neatly and we've avoided all those then calls, but we do need the eventually.
I've provided you a link to a working TypeScript example that might help demonstrate.

Resources