Error while trying to assert getText in WebdriverIO - javascript

I am trying to assert a text that's seen on a media gallery overlay page. All I want is for the code to verify if the text is present and if so, assets it matches the expected text.
For some reason, I keep getting failed tests. Below is the code I have written in Visual Code:
let expSuccessARMessage = "See it in Your Space (Augmented Reality) is currently only available using an AR compatible Apple device (iOS 12 or above)."
let successARMessage = browser.getText(page.pageElements.arMessage);
console.log(successARMessage);
assert(successARMessage === expSuccessARMessage, 'Success message');
What am I missing here?

Not a magician, but you should be getting browser.getText is not a function error in the console, because the getText() method is defined inside the element object, not the browser object. Read the complete API log here.
So your code should be:
let expectedText = "Your long text here"
let foundText = $(page.pageElements.arMessage).getText();
// Considering 'page.pageElements.arMessage' is a valid selector for targeted element
console.log(`Found the following text: ${foundText}`);
assert.equal(expectedText, foundText, 'This is actually the ERROR message');
I want to add to the answer that there can also be a browser object centric approach, using the webdriver protocol API. Thus, our code becomes:
let expectedText = "Your long text here"
let elementObject = browser.findElement('css selector', page.pageElements.arMessage);
// Considering 'page.pageElements.arMessage' is a valid selector for targeted element
let foundText = browser.getElementText(elementObject.ELEMENT);
console.log(`Found the following text: ${foundText}`);
assert.equal(expectedText, foundText, 'This is actually the ERROR message');
The latter approach is obsolete IMHO, and the recommended approach for WebdriverIO v5 would be using $, respectively $$ (element & elements). But wanted to give you a broader perspective.

If you defined the element into object repository like:
get OtpDescriptionText () { return '//div[#class="otp-description"]'; }
In order to console or assert/expect that element you need to use like:
let elem1 = await $(RegistratonPage.OtpDescriptionText);
console.log(await elem1.getText());
or
await expect($(RegistratonPage.OtpDescriptionText)).toHaveTextContaining('We just need to check this phone number belongs to you.')
If you don't use $, error is thrown

Related

How to extract page numbers from Word document via add-in built using the Word JavaScript API

in Word via an add-in built using the Word Javascript API, I'm trying to read the page number of each location a string of text appears in the document text. E.g. the word "HELP" appears on pages 2, 6, 10 and 45. How can I read the page number?
A stripped down version of the code I have so far is:
async function run() {
await Word.run(async (context) => {
let paragraphs = context.document.body.paragraphs;
paragraphs.load("text"); // WHAT ELSE NEEDS TO BE LOADED TO ALLOW PAGE NO EXTRACTION?
await context.sync();
// loop through document to find text
paragraphs.items.forEach((item) => {
let paragraph = item.text.trim();
if (paragraph.includes("EXAMPLE STRING")) {
let pageNumber = what_goes_here?;
console.log("Text found on page: " + pageNumber);
}
});
});
}
This works fine for finding the text string, but I can't work out how to get the page number (pageNumber in the code above).
I've been through the Word API documentation but can't find anything. I can, for example, where the text is in a list extract the list level by loading the "listItemOrNullObject" object and reading the "listString", but I can't see any way to get the page number.
Any ideas? If this isn't available via the standard Word API (as I'm suspecting) has anyone got any workarounds?
I'd like to do this using JS and the Word API (great cross platform support etc.) and not have to use VBA, C# etc.
Thank you!
Currently there hasn't been such an JS API to return the page number of the selected text. You can post the API request here: https://techcommunity.microsoft.com/t5/microsoft-365-developer-platform/idb-p/Microsoft365DeveloperPlatform
Wenjun

webdriver.io no such element

I'm getting no such element error over and over again. I'm working with error more than 7 hours. Dom has the id. But i get error 'no such element'. Here's my code:
describe("Amazon", () => {
it("Search amazon", () => {
browser.url("https://www.amazon.com.tr/");
let searchField = $("#twotabsearchtextbox");
const submit = $("#nav-search-submit-button");
searchField.setValue("mouse");
submit.click();
});
});
And here's the log:
Screenshot of the log
Thanks everyone
This probably means that you are not working in the correct context. You should check if the element is located inside an iframe.
If it's the case, you will need to switch to this iframe context before being able to query the element. You can do so using the WebDriver API 'switch to frame' (W3C webdriver spec) which is available through the webdriver.io API switchToFrame.

How to Select Auto-Generate Classes in Javascript puppeteer?

I'm trying to select the "Use phone / email / username" using puppeteer on the http://tiktok.com/ (you can check out the HTML there) (As referenced below)
At first I thought I could just do
await page.$eval( '.channel-name-2qzLW', form => form.click() );
But the issue is that puppeteer cant find an element with that class because I think the puppeteer browser has a different one as the channel name is automatically generator. As a result I tried finding out how to select an element with the text of Use phone / email / username as that's specific but I ran into issues outlined below.
I tried selecting the divs that contain the text element:
await page.$eval( 'div["Use phone / email / username"]', form => form.click() );
But I received an error message
Error: Evaluation failed: DOMException: Failed to execute 'querySelector' on 'Document': 'div["Use phone or email"]' is not a valid selector.
I've tried looking at https://www.w3schools.com/cssref/css_selectors.asp and https://www.checklyhq.com/learn/headless/basics-selectors/ for an idea of how to get the element but I;m still not sure.
(Current code):
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Goes to tiktok website
await page.goto('https://tiktok.com');
// Clicks on Upload text
await page.$eval( '.upload-text', form => form.click() );
// issue occurs here as it can't find this element
await page.$eval( '.channel-name-2qzLW', form => form.click() );
// screenshots the webpage so I can see what it sees
await page.screenshot({ path: 'browserView.png' });
await browser.close();
})();
Since the class is an attribute, you can use the wildcard selector.
div[class*="channel-name-"]
This selector will target all div elements with classes that partially match "channel-name-".
However, I want to point out that relying on a wildcard selector is not the optimal solution, because if not defined correctly it might return incorrect results. Plus, even though today's machines are fast and strong enough for this tiny extra work, it's still not a very efficient way for a solution, especially with large and complex pages.
So you can use it, but pay more attention.

PHOTOSHOP/JSX: How to efficiently check if tool was used

I am trying to create a small script which will read how many steps were made while editing specific image. While also checking what tools were used. And then export all the results into various categories in .csv.
I have the Output part.
I have the history states.
But how would you check if specific tool e.g.: Liquify, Clone Stamp, Free Transform etc. was used?
I have the below script. Which quickly checks if I used the tool, but if it wasn't used, it throws an error:
No such Element. Line: 13
-> var LiquifyUsed = app.activeDocument.historyStates.getByName('Liquify');
var LiquifyUsed = app.activeDocument.historyStates.getByName('Liquify');
//Check if Liquify was used
if (LiquifyUsed = true) {
alert ("Liquify was used")
} else {
alert ("It was not used")
Simply catch the exception:
var liquifyUsed = false;
try {
app.activeDocument.historyStates.getByName('Liquify');
liquifyUsed = true;
} catch(e) {
// assume the error is always "No such element" --
// you could be more fastidious and check instead.
}
alert('Liquify used: ' + liquifyUsed);

javascript alert not working when API http request has json error (nothing found)

I'm using a thesaurus API,
http://thesaurus.altervista.org
to get synonyms to print to the page. In this demo version,
http://plnkr.co/edit/6pNYlXcgiwxHz00AY5CT?p=preview
it works when you type 'peace', otherwise, in console, if we follow the link, we see a GET error:
{"error":"the key test_only is restricted, please use your own key!"}
(EDIT: to clarify: Demo mode is not the issue. I want to make an alert.) For errors, I want the browser to alert "Oops, word not found. Please choose another word."
Here is the js code from the demo:
//function activated on user input
function myFunc(){
var userInput = document.getElementById('userInput');
var result = userInput.value;
var s = document.createElement("script");
//This demo works with the keyword 'peace' only. So searching for e.g. 'hat' will cause an error.
s.src = "http://thesaurus.altervista.org/service.php?word=" + result + "&language=en_US&output=json&key=test_only&callback=process"; // NOTE: replace test_only with your own KEY
document.getElementsByTagName("head")[0].appendChild(s);
window.process = function (result) {
//my attempt at throwing an error
if(result.error){alert("Oops, word not found. Please choose another word.");}
//normal processing..
output = "";
for (key in result.response) {
list = result.response[key].list;
output += list.synonyms+"<br>";
}
if (output)
document.getElementById("synonyms").innerHTML = output;
}
}
I did some research and found this answer (it's jQuery but mine's not but it might be relevant?):
https://stackoverflow.com/a/2568788
Any help much appreciated, thanks.
It's because you need to generate your own key. The key you are using is just a sample key.
Right there.
Then you'll change test_only is the URL by the generated key.
Anyhow, that perhaps means that the service is not free of use, so be careful and read the license if you plan to use it commercially.
You need to replace the test API key with your API key.
You can get your API key by going to http://thesaurus.altervista.org/mykey and signing up or logging in.
You even have a comment in your code telling you to do this:
s.src = "http://thesaurus.altervista.org/service.php?word=" + result + "&language=en_US&output=json&key=test_only&callback=process";
// NOTE: replace test_only with your own KEY
So if your API key 123456789, your URL will look like this:
s.src = "http://thesaurus.altervista.org/service.php?word=" + result + "&language=en_US&output=json&key=123456789&callback=process";

Categories

Resources