I’m working on a UK Government project at the moment that has a lot of Cypress tests. The way they are set up is not exactly to my taste, but I mention it because it is relevant to the way the code will be structured below. However, the method I use to remove lines from strings in Cypress doesn’t change too much regardless.
OK, so the problem is basically this:
But when Cypress runs the test, it fails because the actual text in the HTML is more like this:
And you might think that’s nonsense, but because of HTML reformatters and such like, it is pretty common longer strings. At least, it has bitten me on multiple projects.
Removing Line Breaks In Cypress Tests
Cypress has had the ability to remove leading and trailing spaces in their assertions since as far back as version
So if all you have to worry about is text like this:
Then you should have no problem.
This problem specifically comes in when the text has line break characters added in the HTML – those pesky
One way to address this is with a regex match directly in your assertion:
And this will work, and is most of the solution.
But if you have multiple places that you need to do this – and I frequently do – then we really do need to go one step further and extract out the regex replace into a helper function.
Creating A Helper Function
How you set this up is up to you and your project. There may be an existing place with common / shared test code.
In my case this code lives in a file under the
In there, amongst other things I add this:
As you can see, it’s not a TypeScript project 🙁
Refactoring The Test(s)
With the helper function created, it’s now a case of importing the
cleanString function into as many tests as needed, and calling the function in the assertion:
And that’s it.
A slightly improved test setup to remove new lines from strings when testing in Cypress.