Skip to content

Commit

Permalink
feat: show how to compare text from two elements (#188)
Browse files Browse the repository at this point in the history
  • Loading branch information
bahmutov committed Jan 15, 2019
1 parent bf9fdf1 commit 0f49490
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
43 changes: 43 additions & 0 deletions app/commands/assertions.html
Expand Up @@ -336,6 +336,49 @@ <h3><a href="https://on.cypress.io/should#Function" target="_blank">Should with
})</code></pre>
</div>

<div class="col-xs-12">
<p>
We <a href="https://on.cypress.io/conditional-testing">strongly recommend that your tests are deterministic</a>.
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 <code>should(cb)</code> callback.
</p>
</div>

<div class="col-xs-7">
<pre><code class="javascript">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)
})</code></pre>
</div>

<div class="col-xs-5">
<div class="well">
<div class="two-elements">
<div class="first">Foo Bar</div>
<div class="second">foo b a r</div>
</div>
</div>
</div>

<div class="col-xs-12"><hr /></div>
</div>
</div>
Expand Down
30 changes: 30 additions & 0 deletions cypress/integration/examples/assertions.spec.js
Expand Up @@ -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',
Expand Down

0 comments on commit 0f49490

Please sign in to comment.