spectator
spectator copied to clipboard
Better toHaveExactText
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
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
@matheo do you have any thoughts on this issue?
@levsim2016 seems legit to have an option to trim these cases, cc @keitoaino
This looks to have been addressed in the above PR. Can this be closed now?