Why can't I use querySelector in protractor? - javascript

I am using protractor. I understand that protractor has Jquery like syntax but I need something that can
create conditions, variables and loops based on DOM elements in some of my testing. I want to be able to use querySelector. Using just promises won't let me do the kind of testing I need to do.
When I run it, it says:
Failed: Cannot read property 'querySelector' of undefined
or
Failed: document is not defined
or
Failed: window is not defined
I've set up a test to test this issue. It runs off a random web page that I was looking at it. It selects the footer using protractor and then attempts it using querySelector. If I enter the querySelector portion in the console, it runs the code correctly. I've also tried variations of querySelector, using window.document; this also works in the browser but not in protractor.
describe("Test", function()
{
it('This is a test to test protractor' , function()
{
browser.waitForAngularEnabled(false);
browser.get("https://facebook.github.io/jest/");
$("#footer").getAttribute("innerHTML").then( function(value)
{
console.log("inside value then");
console.log(value);
});
var queryse = document.querySelector("#footer").innerHTML;
// var queryse = browser.document.querySelector("#footer").innerHTML;
// var queryse = window.document.querySelector("#footer").innerHTML;
console.log('query selector');
console.log(queryse);
});
});

The code you're running in Protractor test case doesn't really run in browser, in fact it's executed in Node.js. You should think of it as an API that will afterwards communicate with the browser through WebDriver. That means that you cannot use browser specific JavaScript API in the code. The $ helper is just there to make the syntax easy and understandable without knowing anything about Selenium. That's why document and window are inaccessible for you. If you want to read more about that: https://github.com/angular/protractor/blob/master/docs/locators.md

#Nhor's answer is mostly correct in terms of the environments and why you cannot use document and window directly. However, for what it's worth, you can definitely find elements in the DOM through executeScript. The only question is, why do you need to do this?
Any locator you can use in the DOM, you can use in Protractor (though the syntax might be different). Here's an example, I used innerHTML because that's what you were trying in your case:
describe('Protractor Demo App', function() {
it('element test', function() {
browser.get('http://juliemr.github.io/protractor-demo/');
var el = browser.executeScript('return document.querySelector("h3").innerHTML');
el.then(function (text) {
console.log(text); // logs "Super Calculator"
});
});
});
Finally, it's important to note that this el is restricted to javascript functions from within that executeScript call. It is not a version of Protractor's ElementFinder, you cannot perform actions like getText() on it (though it is still a Promise, so you need to call .then()). You can do a console log on the el to see what's in that object.

Related

Protractor - getting computed style from web element using browser.executeScript works with string but fails with function

I'm trying to verify visibility for a tooltip popup by calling window.getComputedStyle().visibility property using protractor framework.
When I pass a string to executeScript it's working fine. It's returning visible:
// elementToCheck is an ElementFinder
async getComputedStyleVisibility(elementToCheck) {
return await browser
.executeScript(`return window.getComputedStyle(document.querySelector('${elementToCheck.locator().value}')).visibility`);
}
However, this is failing when I replace the string within executeScript by a function. It's returning hidden and it looks like execution gets stuck until tooltip popup disappears.
So I guess there's some synchronisation issue, but I cannot figure out what's happening:
// elementToCheck is an ElementFinder
async getComputedStyleVisibility(elementToCheck) {
return await browser.executeScript(
webElem => (window.getComputedStyle(webElem).visibility),
await elementToCheck.getWebElement()
);
}
For making your script work as you wanted, you need to correctly access your webElement.
The docs say,
Any arguments provided in addition to the script will be included as script arguments and may be referenced using the arguments object
So you need to use arguments object in your script. Like so:
async getComputedStyleVisibility(elementToCheck) {
return await browser.executeScript(
() => (window.getComputedStyle(arguments[0]).visibility),
await elementToCheck.getWebElement()
);
}
BUT
If you aren't restricted in some way to only use browser.executeScript() then you should overthink your approach.
protractor provides an API for checking if a certain element is present or similar.
Check an element to be present and visible for user:
element(by.css("#a")).isDisplayed()
.then(isDisplayed => console.log("element displayed?", isDisplayed))
.catch(err => console.error("Some error happedn. Element not present..", err))
You should use browser.executeScript() only as last resort in my opinion. Most of the general stuff like clicking, checking if present, etc. is already there, in a handy way, provided by protractor.

Protractor - Giving "could not find testability for element" error when accessing element

I'm running into issue with Protractor when accessing variable that stores return value of "elements.all". I'm fairly new to Protractor, so I wasn't sure how to select elements by custom attribute. Luckily, I received a suggestion, when I posted a question in another post. I was suggested to try out - "element.all(by.css('[mycustom-id]'));". But I'm not sure if that statement works or not since I'm getting "Could not find testability for element" error. It is also possible that I'm incorrectly iterating the object. I appreciate if anyone of you can point out my mistake. Thanks.
Spec.JS
var settings = require(__dirname + '/setting.json');
describe('Protractor Demo App', function() {
var target = element.all(by.css('[mycustom-id]'));
beforeEach(function() {
browser.get(settings.url);
});
it('Test mouseover', function() {
// This does not work
target.each(function(item){
//Do some stuff here
});
// This does not work either
target.count().then(function(x){
console.log("Total--" + x);
});
});
});
index.html
<div>
<a mycustom-id="123" href=''>HELLO1</a>
<a mycustom-id="211" href=''>HELLO2</a>
</div>
I'm getting this error because I need to set useAllAngular2AppRoots to true in config file. So if anyone having similar issue, make sure you have useAllAngular2AppRoots set to True.
It's not a good practice to put things outside of Jasmine functions, i.e. outside of it(), beforeAll() etc. Protractor uses those Jasmine functions to manage the control flow.
So I'm guessing that it is trying to create those webElements way before it should be. Move your element locator inside the it() block.
it('Test mouseover', function() {
var target = element.all(by.css('[mycustom-id]'));
target.each(function(item){
//Do some stuff here
});
});

How do I get a webcam working with AngularJS?

Previously I've put working webcam code into my application, but now it's not working when I updated to AngularJS v1.5.0. I am using webcam-directive which was working perfectly with v1.3.0.
Here is my code:
<webcam placeholder="selfiePlaceHolder"
on-stream="onStream(stream)"
on-access-denied="onError(err)" on-streaming="onSuccess(video)">
</webcam>
But now it's giving following error with AngularJS v1.5.0:
Uncaught Error: [$parse:isecdom] Referencing DOM nodes in Angular expressions is disallowed! Expression: onSuccess(video)
http://errors.angularjs.org/1.5.0/$parse/isecdom?p0=onSuccess(video)
I also tried to use a different solution with AngularJS ng-Camera but even its demo page is not working for me.
Note: I know the issue is that we can't access the DOM from the newer version of AngularJS, but the same code works with the older version. I need to know how to pass the "Video" DOM object to the controller.
I've found the solution to the problem. Two things need to be done:
First In HTML:
<webcam channel="channel"
on-streaming="onSuccess()"
on-error="onError(err)"
on-stream="onStream(stream)"></webcam>
Secondly, in the controller, you can access the DOM video with the following code:
$scope.onSuccess = function () {
// The video element contains the captured camera data
_video = $scope.channel.video;
$scope.$apply(function() {
$scope.patOpts.w = _video.width;
$scope.patOpts.h = _video.height;
//$scope.showDemos = true;
});
};
Here is a working example.
It is a potential error generally occurs when an expression tries to access a DOM node since it is restricted accessing to DOM nodes via expressions by AngularJS because it might cause to execute arbitrary Javascript code.
The $parse:isecdom error is related to an invoke to a function by event handler when an event handler which returns a DOM node, like below:
<button ng-click="myFunction()">Click</button>
$scope.myFunction = function() {
return DOM;
}
To fix this issue, avoid access to DOM nodes and avoid returning DOM nodes from event handlers. (Reference: https://docs.angularjs.org/error/$parse/isecdom)
Adding an explicit return might solve this issue as detailed here: CoffeeScript - Referencing DOM nodes in Angular expressions is disallowed
I was able to get webcam-directive working using the channel suggestion from the comment above, based on the example on the github page.
function MyController($scope) {
$scope.myChannel = {
// the fields below are all optional
videoHeight: 800,
videoWidth: 600,
video: null // Will reference the video element on success
};
}
In the onSuccess(on-streaming attr) and onStream(on-stream attr) callback the video property of myChannel was filled in with the video DOM element (and then it would obviously be available to everything else in the controller too). According to the comment in the example code though, you should wait to access it at least until onSuccess. Here is a working example

Protractor/Jasmine test browser.isElementPresent not working when looking for a class

So i'm trying to run some tests with jasmine but i'm fairly new to the whole thing. I've spent way more time than i'm willing to admit trying to work out why my my webdriver is closing the browser before it has a chance to check the '.detailsColumn' element for expected results. After a while I've worked out that i can use browser.wait to make the browser stay alive long enough for the element to be ready.
My latest version of the test is below. The error I get is an invalidSelectorError and no info about which line the error was thrown on. I'd hazard a guess that the invalidSelectorError points to either my declaration or use of the detailsColumn variable though.
Can anyone see why this wouldn't work? I'm at a loss.
I'm using protractor/jasmine to do my tests, and using selenium for my web driver.
it('Should display result summary correctly when searching for multiple articles only', function () {
var TrackID= ExpectedArticle1Details.TrackingID + ', ' + ExpectedArticle2Details.TrackingID;
landingPage.get();
landingPage.setTrackID(TrackID)
landingPage.clickTrackButton();
expect(resultPage.allElementsofLandingPageAreVisible()).toEqual(true);
expect(resultPage.allHeadersofResultsPageAreVisible()).toEqual(true);
browser.wait(function () {
var detailsColumn = protractor.By.css('.detailsColumn.status:eq(0)');
return browser.isElementPresent(detailsColumn).then(function (result) {
expect(result).toBe(true);
return result;
console.log(result);
});
}, 10000);
JQuery index-related selectors like eq() are not supported by selenium webdriver.
You probably want to use nth-child instead:
.detailsColumn.status:nth-child(1)
Or, you may even replace it with element.all() plus first():
element.all(by.css(".detailsColumn.status")).first();
Additionally, if you have to use browser.wait(), I think you can replace the whole browser.wait() block you currently have with:
var EC = protractor.ExpectedConditions;
var detailsColumn = element(by.css('.detailsColumn.status:nth-child(1)'));
browser.wait(EC.presenceOf(detailsColumn), 10000);

How can I attach an event handler to the process's exit in a native Node.js module?

I'm working on implementing correct memory management for a native Node.js module. I've ran into the problem described in this question:
node.js native addon - destructor of wrapped class doesn't run
The suggested solution is to bind the destructors of native objects to process.on('exit'), however the answer does not contain how to do that in a native module.
I've taken a brief look at the libuv docs as well, but they didn't contain anything useful in this regard, either.
NOTE: I'm not particularly interested in getting the process object, but I tried it that way:
auto globalObj = NanGetCurrentContext()->Global();
auto processObj = ::v8::Handle<::v8::Object>::Cast(globalObj->Get(NanNew<String>("process")));
auto processOnFunc = ::v8::Handle<::v8::Function>::Cast(processObj->Get(NanNew<String>("on")));
Handle<Value> processOnExitArgv[2] = { NanNew<String>("exit"), NanNew<FunctionTemplate>(onProcessExit)->GetFunction() };
processOnFunc->Call(processObj, 2, processOnExitArgv);
The problem then is that I get this message when trying to delete my object:
Assertion `persistent().IsNearDeath()' failed.
I also tried to use std::atexit and got the same assertion error.
So far, the best I could do is collecting stray ObjectWrap instances in an std::set and cleaning up the wrapped objects, but because of the above error, I was unable to clean up the wrappers themselves.
So, how can I do this properly?
I was also getting the "Assertion persistent().IsNearDeath()' failed" message.
There is a node::AtExit() function that runs just before Node.js shuts down - the equivalent of process.on('exit').
Pass a callback function to node::AtExit from within your add-on's init function (or where ever is appropriate).
The function is documented here:
https://nodejs.org/api/addons.html#addons_atexit_hooks
For example:
NAN_MODULE_INIT(my_exports)
{
// other exported stuff here
node::AtExit(my_cleanup);
}
NODE_MODULE(my_module, my_exports) //add-on exports
//call C++ dtors:
void my_cleanup()
{
delete my_object_ptr; //call object dtor, or other stuff that needs to be cleaned up here
}

Categories

Resources