spectator icon indicating copy to clipboard operation
spectator copied to clipboard

Better toHaveExactText

Open grosch opened this issue 2 years ago • 4 comments

Description

The toHaveExactText test is pretty fragile. If I use this HTML

<some-tag>hello</some-tag>

Then I can safely expect(spectator.query('some-tag')).toHaveExactText('hello').

However, as soon as some-tag gets a ton of new attributes, and then somebody's IDE reformats like so:

<some-tag lots of attributes here>
  hello
</some-tag>

Then the test fails. I don't think that it should, because what I'm testing is for the text that's visible. In the second example, the DOM returns that string as ' hello ', i.e. there's a single space at the start and end.

I can't use toHaveText instead because that does a contains check, vs. an actual "does this string match". As an example, toHaveText would return true if the text was actually "Othello" because it's then doing a contains.

Proposed solution

Add a second optional parameter to toHaveExactText that specifies whether or not to trim the text. It would of course default to false to prevent any existing code base from breaking.

Alternatives considered

Could have something like toHaveExactTrimmedText

Do you want to create a pull request?

No

grosch avatar Jul 03 '22 08:07 grosch

That would be really nice to have this. I have similar problems by using just toHaveText, so instead i use something similar to expect(spectator.query('.some-class').textContent.trim()).toBe('expected text'). In my opinion that's uncomfortable

levsim2016 avatar Jul 11 '22 21:07 levsim2016

@matheo do you have any thoughts on this issue?

levsim2016 avatar Oct 03 '22 11:10 levsim2016

@levsim2016 seems legit to have an option to trim these cases, cc @keitoaino

matheo avatar Oct 03 '22 23:10 matheo

This looks to have been addressed in the above PR. Can this be closed now?

TheSteinn avatar May 17 '23 09:05 TheSteinn