Recently, a guy asked me below question:
I need to verify title of an article is in bold. Article title has no <b> or <strong> tag. How to verify it now?
It was also new to me and learnt new thing that day. So I am sharing my knowledge here.
HTML provides two tags to make text bold:- b and strong.
In above case you can easily locate the text and get tag name. You can assert tag name as “b” or “strong”.
This paragraph is made in bold using html 'b' tag. This paragraph is made in bold using html 'strong' tag.
But CSS provides an attribute called “font-weight” which is more powerful. You can assign this to html element with values. You can make text normal, bold and bolder. Refer all possible values here.
If you have bold text using above css attribute, you need to retrieve this from element and assert as expected.
Sample HTML code:
Making text bold using different ways
This paragraph is made in bold using html 'b' tag. This paragraph is made in bold using html 'strong' tag.This paragraph is made in bold using css attribute named font-weight.
Java Program:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
public class VerifyTextInBold {
public static void main(String[] args) {
// Launching browser and load html file
System.setProperty("webdriver.chrome.driver","./exefiles/chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("file:///C:/Users/amodm/fontWeight.html");
// Assert tag name of bold text
String tagName= driver.findElement(By.id("bold1")).getTagName();
Assert.assertEquals(tagName, "b");
// Assert tag name of bold text
String tagName1= driver.findElement(By.id("bold2")).getTagName();
Assert.assertEquals(tagName1, "strong");
// Get value of font-weight and assert if it is bold
String fontWeight= driver.findElement(By.id("bold3")).getCssValue("font-weight");
System.out.println(fontWeight);
Assert.assertTrue(Integer.parseInt(fontWeight)>700);
driver.quit();
}
}
In above example, I consider bold text but you can change it as per your requirement. If you are confused with how to get css value- Read this post.
In case of any doubt, suggestion or you find some mistake, feel free to let me know in comments.
#ThanksForReading