From 80f50bcef286cd3bf48b7c49228ab7e98f8b90df Mon Sep 17 00:00:00 2001 From: Gleb Bahmutov Date: Wed, 17 Nov 2021 11:27:09 -0500 Subject: [PATCH] feat: add cy.contains example with duplicate white spaces --- docs/commands/querying.md | 41 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/docs/commands/querying.md b/docs/commands/querying.md index e44cb31a4..fde2e5728 100644 --- a/docs/commands/querying.md +++ b/docs/commands/querying.md @@ -496,7 +496,7 @@ Even if there are optional white space characters around the text, you can still -Note the whitespace around the word "Incredible" +Note the whitespace around the word "Incredible" ```html
Incredible
@@ -512,6 +512,45 @@ cy.contains('.nickname', /^\s*Incredible\s*$/) +### cy.contains with duplicate white spaces + +If the HTML element contains duplicate white spaces, using `cy.contains` becomes trickier. The example below has a double space between the `:` and `b` characters. + + + + + +```html +
LEGO: blocks
+``` + +If you inspect this element in the browser's console, you will see that the browser returns different strings for `innerHTML` and `innerText` properties - and the browser collapses multiple spaces into one. + +```text +> $0.innerText.length +> 12 +> $0.innerHTML.length +> 13 +``` + +If you are using the literal string for matching, the `cy.contains` will fail, since it uses the `innerText` property. + +```js +// FAILS, cannot find the element while having " " double space +// cy.contains('#spaces', 'LEGO: blocks') +// solution: find the element and assert its text yourself +cy.get('#spaces').should($el => { + expect($el).to.have.html('LEGO: blocks') +}) +// you can also remove duplicate white spaces before calling cy.contains +// and for good measure trimp the text we are looking for +cy.contains('#spaces', 'LEGO: blocks'.replace(/\s+/, ' ').trim()) +``` + + + + + ### Extract part of the text Once you found an element with some text, you can extract a specific part using a regular expression with [named groups](https://caniuse.com/mdn-javascript_builtins_regexp_named_capture_groups), which are supported by the modern browsers.