-
Notifications
You must be signed in to change notification settings - Fork 409
feat: implement toHaveSelection #637
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
gnapse
merged 3 commits into
testing-library:main
from
silviuaavram:pr/finish-to-have-selection
Oct 16, 2024
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,189 @@ | ||
import {render} from './helpers/test-utils' | ||
|
||
describe('.toHaveSelection', () => { | ||
test.each(['text', 'password', 'textarea'])( | ||
'handles selection within form elements', | ||
testId => { | ||
const {queryByTestId} = render(` | ||
<input type="text" value="text selected text" data-testid="text" /> | ||
<input type="password" value="text selected text" data-testid="password" /> | ||
<textarea data-testid="textarea">text selected text</textarea> | ||
`) | ||
|
||
queryByTestId(testId).setSelectionRange(5, 13) | ||
expect(queryByTestId(testId)).toHaveSelection('selected') | ||
|
||
queryByTestId(testId).select() | ||
expect(queryByTestId(testId)).toHaveSelection('text selected text') | ||
}, | ||
) | ||
|
||
test.each(['checkbox', 'radio'])( | ||
'returns empty string for form elements without text', | ||
testId => { | ||
const {queryByTestId} = render(` | ||
<input type="checkbox" value="checkbox" data-testid="checkbox" /> | ||
<input type="radio" value="radio" data-testid="radio" /> | ||
`) | ||
|
||
queryByTestId(testId).select() | ||
expect(queryByTestId(testId)).toHaveSelection('') | ||
}, | ||
) | ||
|
||
test('does not match subset string', () => { | ||
const {queryByTestId} = render(` | ||
<input type="text" value="text selected text" data-testid="text" /> | ||
`) | ||
|
||
queryByTestId('text').setSelectionRange(5, 13) | ||
expect(queryByTestId('text')).not.toHaveSelection('select') | ||
expect(queryByTestId('text')).toHaveSelection('selected') | ||
}) | ||
|
||
test('accepts any selection when expected selection is missing', () => { | ||
const {queryByTestId} = render(` | ||
<input type="text" value="text selected text" data-testid="text" /> | ||
`) | ||
|
||
expect(queryByTestId('text')).not.toHaveSelection() | ||
|
||
queryByTestId('text').setSelectionRange(5, 13) | ||
|
||
expect(queryByTestId('text')).toHaveSelection() | ||
}) | ||
|
||
test('throws when form element is not selected', () => { | ||
const {queryByTestId} = render(` | ||
<input type="text" value="text selected text" data-testid="text" /> | ||
`) | ||
|
||
expect(() => | ||
expect(queryByTestId('text')).toHaveSelection(), | ||
).toThrowErrorMatchingInlineSnapshot( | ||
` | ||
<dim>expect(</><red>element</><dim>).toHaveSelection(</><green>expected</><dim>)</> | ||
|
||
Expected the element to have selection: | ||
<green> (any)</> | ||
Received: | ||
|
||
`, | ||
) | ||
}) | ||
|
||
test('throws when form element is selected', () => { | ||
const {queryByTestId} = render(` | ||
<input type="text" value="text selected text" data-testid="text" /> | ||
`) | ||
queryByTestId('text').setSelectionRange(5, 13) | ||
|
||
expect(() => | ||
expect(queryByTestId('text')).not.toHaveSelection(), | ||
).toThrowErrorMatchingInlineSnapshot( | ||
` | ||
<dim>expect(</><red>element</><dim>).not.toHaveSelection(</><green>expected</><dim>)</> | ||
|
||
Expected the element not to have selection: | ||
<green> (any)</> | ||
Received: | ||
<red> selected</> | ||
`, | ||
) | ||
}) | ||
|
||
test('throws when element is not selected', () => { | ||
const {queryByTestId} = render(` | ||
<div data-testid="text">text</div> | ||
`) | ||
|
||
expect(() => | ||
expect(queryByTestId('text')).toHaveSelection(), | ||
).toThrowErrorMatchingInlineSnapshot( | ||
` | ||
<dim>expect(</><red>element</><dim>).toHaveSelection(</><green>expected</><dim>)</> | ||
|
||
Expected the element to have selection: | ||
<green> (any)</> | ||
Received: | ||
|
||
`, | ||
) | ||
}) | ||
|
||
test('throws when element selection does not match', () => { | ||
const {queryByTestId} = render(` | ||
<input type="text" value="text selected text" data-testid="text" /> | ||
`) | ||
queryByTestId('text').setSelectionRange(0, 4) | ||
|
||
expect(() => | ||
expect(queryByTestId('text')).toHaveSelection('no match'), | ||
).toThrowErrorMatchingInlineSnapshot( | ||
` | ||
<dim>expect(</><red>element</><dim>).toHaveSelection(</><green>no match</><dim>)</> | ||
|
||
Expected the element to have selection: | ||
<green> no match</> | ||
Received: | ||
<red> text</> | ||
`, | ||
) | ||
}) | ||
|
||
test('handles selection within text nodes', () => { | ||
const {queryByTestId} = render(` | ||
<div> | ||
<div data-testid="prev">prev</div> | ||
<div data-testid="parent">text <span data-testid="child">selected</span> text</div> | ||
<div data-testid="next">next</div> | ||
</div> | ||
`) | ||
|
||
const selection = queryByTestId('child').ownerDocument.getSelection() | ||
const range = queryByTestId('child').ownerDocument.createRange() | ||
selection.removeAllRanges() | ||
selection.empty() | ||
selection.addRange(range) | ||
|
||
range.selectNodeContents(queryByTestId('child')) | ||
|
||
expect(queryByTestId('child')).toHaveSelection('selected') | ||
expect(queryByTestId('parent')).toHaveSelection('selected') | ||
|
||
range.selectNodeContents(queryByTestId('parent')) | ||
|
||
expect(queryByTestId('child')).toHaveSelection('selected') | ||
expect(queryByTestId('parent')).toHaveSelection('text selected text') | ||
|
||
range.setStart(queryByTestId('prev'), 0) | ||
range.setEnd(queryByTestId('child').childNodes[0], 3) | ||
|
||
expect(queryByTestId('prev')).toHaveSelection('prev') | ||
expect(queryByTestId('child')).toHaveSelection('sel') | ||
expect(queryByTestId('parent')).toHaveSelection('text sel') | ||
expect(queryByTestId('next')).not.toHaveSelection() | ||
|
||
range.setStart(queryByTestId('child').childNodes[0], 3) | ||
range.setEnd(queryByTestId('next').childNodes[0], 2) | ||
|
||
expect(queryByTestId('child')).toHaveSelection('ected') | ||
expect(queryByTestId('parent')).toHaveSelection('ected text') | ||
expect(queryByTestId('prev')).not.toHaveSelection() | ||
expect(queryByTestId('next')).toHaveSelection('ne') | ||
}) | ||
|
||
test('throws with information when the expected selection is not string', () => { | ||
const {container} = render(`<div>1</div>`) | ||
const element = container.firstChild | ||
const range = element.ownerDocument.createRange() | ||
range.selectNodeContents(element) | ||
element.ownerDocument.getSelection().addRange(range) | ||
|
||
expect(() => | ||
expect(element).toHaveSelection(1), | ||
).toThrowErrorMatchingInlineSnapshot( | ||
`expected selection must be a string or undefined`, | ||
) | ||
}) | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
import isEqualWith from 'lodash/isEqualWith' | ||
import {checkHtmlElement, compareArraysAsSet, getMessage} from './utils' | ||
|
||
/** | ||
* Returns the selection from the element. | ||
* | ||
* @param element {HTMLElement} The element to get the selection from. | ||
* @returns {String} The selection. | ||
*/ | ||
function getSelection(element) { | ||
const selection = element.ownerDocument.getSelection() | ||
|
||
if (['input', 'textarea'].includes(element.tagName.toLowerCase())) { | ||
if (['radio', 'checkbox'].includes(element.type)) return '' | ||
return element.value | ||
.toString() | ||
.substring(element.selectionStart, element.selectionEnd) | ||
} | ||
|
||
if (selection.anchorNode === null || selection.focusNode === null) { | ||
// No selection | ||
return '' | ||
} | ||
|
||
const originalRange = selection.getRangeAt(0) | ||
const temporaryRange = element.ownerDocument.createRange() | ||
|
||
if (selection.containsNode(element, false)) { | ||
// Whole element is inside selection | ||
temporaryRange.selectNodeContents(element) | ||
selection.removeAllRanges() | ||
selection.addRange(temporaryRange) | ||
} else if ( | ||
element.contains(selection.anchorNode) && | ||
element.contains(selection.focusNode) | ||
) { | ||
// Element contains selection, nothing to do | ||
} else { | ||
// Element is partially selected | ||
const selectionStartsWithinElement = | ||
element === originalRange.startContainer || | ||
element.contains(originalRange.startContainer) | ||
const selectionEndsWithinElement = | ||
element === originalRange.endContainer || | ||
element.contains(originalRange.endContainer) | ||
selection.removeAllRanges() | ||
|
||
if (selectionStartsWithinElement || selectionEndsWithinElement) { | ||
temporaryRange.selectNodeContents(element) | ||
|
||
if (selectionStartsWithinElement) { | ||
temporaryRange.setStart( | ||
originalRange.startContainer, | ||
originalRange.startOffset, | ||
) | ||
} | ||
if (selectionEndsWithinElement) { | ||
temporaryRange.setEnd( | ||
originalRange.endContainer, | ||
originalRange.endOffset, | ||
) | ||
} | ||
|
||
selection.addRange(temporaryRange) | ||
} | ||
} | ||
|
||
const result = selection.toString() | ||
|
||
selection.removeAllRanges() | ||
selection.addRange(originalRange) | ||
|
||
return result | ||
} | ||
|
||
/** | ||
* Checks if the element has the string selected. | ||
* | ||
* @param htmlElement {HTMLElement} The html element to check the selection for. | ||
* @param expectedSelection {String} The selection as a string. | ||
*/ | ||
export function toHaveSelection(htmlElement, expectedSelection) { | ||
checkHtmlElement(htmlElement, toHaveSelection, this) | ||
|
||
const expectsSelection = expectedSelection !== undefined | ||
|
||
if (expectsSelection && typeof expectedSelection !== 'string') { | ||
throw new Error(`expected selection must be a string or undefined`) | ||
} | ||
|
||
const receivedSelection = getSelection(htmlElement) | ||
|
||
return { | ||
pass: expectsSelection | ||
? isEqualWith(receivedSelection, expectedSelection, compareArraysAsSet) | ||
: Boolean(receivedSelection), | ||
message: () => { | ||
const to = this.isNot ? 'not to' : 'to' | ||
const matcher = this.utils.matcherHint( | ||
`${this.isNot ? '.not' : ''}.toHaveSelection`, | ||
'element', | ||
expectedSelection, | ||
) | ||
return getMessage( | ||
this, | ||
matcher, | ||
`Expected the element ${to} have selection`, | ||
expectsSelection ? expectedSelection : '(any)', | ||
'Received', | ||
receivedSelection, | ||
) | ||
}, | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.