I recently wrote a test which required comparing a "Yes/No" displayed value to a true/false database value.
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 in to 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')
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');
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.