Converting 'Yes'/'No' value to true/false in assertions

klamping

Kevin Lamping

Posted on October 10, 2018

Converting 'Yes'/'No' value to true/false in assertions

I recently wrote a test which required comparing a "Yes/No" displayed value to a true/false database value.

Example HTML table mapping to the Database Schema.

It wasn't a completely trivial task, so I decided to share the solution I came up with.

This example uses Chai's 'expect' assertion syntax.

Here's my initial attempt at it, which is incomplete for reasons I'll go into next.

const displayedValue = browser.getText('.is-allowed'); // returns 'Yes'

// pretend 'db' is some magic database call that's all wired up
const databaseValue = db.getValue('isAllowed'); // returns true

expect(displayedValue === 'Yes').to.equal(databaseValue, 'Displayed value matches database')
Enter fullscreen mode Exit fullscreen mode

This is pretty good, but won't catch issues in the display value if the databaseValue is false.

For example, if our isAllowed database value is false, then anything other than 'Yes' in that displayed value will result in a passing test (e.g. an invalid value that's misspelled, like 'Yess', would still pass).

Instead, here's a more resilient variation, where we validate that the text is either 'Active' or 'Inactive' depending on the database value:

const displayedValue = browser.getText('.status'); // returns 'Inactive'

const databaseValue = db.getValue('isActive'); // returns false

expect(displayedValue).to.equal(isActive ? 'Active' : 'Inactive');
Enter fullscreen mode Exit fullscreen mode

This version helps lock down the possible allowed values being displayed. It only passes if the exact text matches for either database value.

Notice we also don't need to add an assertion message, as the values we're passing in are all the information we need.

If you're unfamiliar with the ternary statement at the end, check out this insightful post.

Header Photo by Jon Tyson on Unsplash

💖 💪 🙅 🚩
klamping
Kevin Lamping

Posted on October 10, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related