From 0f49490c67e547289102ff5ccefced1b507c64ed Mon Sep 17 00:00:00 2001 From: Gleb Bahmutov Date: Tue, 15 Jan 2019 09:31:31 -0500 Subject: [PATCH] feat: show how to compare text from two elements (#188) --- app/commands/assertions.html | 43 +++++++++++++++++++ .../integration/examples/assertions.spec.js | 30 +++++++++++++ 2 files changed, 73 insertions(+) diff --git a/app/commands/assertions.html b/app/commands/assertions.html index 863e155c8..39dfe92d0 100644 --- a/app/commands/assertions.html +++ b/app/commands/assertions.html @@ -336,6 +336,49 @@

Should with }) +
+

+ We strongly recommend that your tests are deterministic. + But sometimes you might need to match text between two elements, and you + do not know what that text should be. Save the value from the first element, + then compare it from a should(cb) callback. +

+
+ +
+
let text
+/**
+* Normalizes passed text,
+* useful before comparing text with spaces and different capitalization.
+* @param {string} s Text to normalize
+*/
+const normalizeText = (s) => s.replace(/\s/g, '').toLowerCase()
+
+cy.get('.two-elements')
+.find('.first')
+.then(($first) => {
+  // save text from the first element
+  text = normalizeText($first.text())
+})
+
+cy.get('.two-elements')
+.find('.second')
+.should(($div) => {
+  // we can massage text before comparing
+  const secondText = normalizeText($div.text())
+  expect(secondText, 'second text').to.equal(text)
+})
+
+ +
+
+
+
Foo Bar
+
foo b a r
+
+
+
+

diff --git a/cypress/integration/examples/assertions.spec.js b/cypress/integration/examples/assertions.spec.js index 299425860..e882bb3ce 100644 --- a/cypress/integration/examples/assertions.spec.js +++ b/cypress/integration/examples/assertions.spec.js @@ -124,6 +124,36 @@ context('Assertions', () => { }) }) + it('matches unknown text between two elements', () => { + /** + * Text from the first element. + * @type {string} + */ + let text + + /** + * Normalizes passed text, + * useful before comparing text with spaces and different capitalization. + * @param {string} s Text to normalize + */ + const normalizeText = (s) => s.replace(/\s/g, '').toLowerCase() + + cy.get('.two-elements') + .find('.first') + .then(($first) => { + // save text from the first element + text = normalizeText($first.text()) + }) + + cy.get('.two-elements') + .find('.second') + .should(($div) => { + // we can massage text before comparing + const secondText = normalizeText($div.text()) + expect(secondText, 'second text').to.equal(text) + }) + }) + it('assert - assert shape of an object', () => { const person = { name: 'Joe',