Skip to content
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

Add toHaveSelection #412

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
70 changes: 70 additions & 0 deletions src/__tests__/to-have-selection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
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('handles selection within text nodes', () => {
const {queryByTestId} = render(`
<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>
`)

const selection = queryByTestId('child').ownerDocument.getSelection()
const range = queryByTestId('child').ownerDocument.createRange()
selection.removeAllRanges()
selection.addRange(range)

range.selectNodeContents(queryByTestId('child'))

expect(queryByTestId('parent')).toHaveSelection('selected')

range.setStart(queryByTestId('prev'), 0)
range.setEnd(queryByTestId('child').childNodes[0], 3)

expect(queryByTestId('parent')).toHaveSelection('text sel')

range.setStart(queryByTestId('child').childNodes[0], 3)
range.setEnd(queryByTestId('next').childNodes[0], 4)

expect(queryByTestId('parent')).toHaveSelection('ected text')
})
})
2 changes: 2 additions & 0 deletions src/matchers.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {toBeChecked} from './to-be-checked'
import {toBePartiallyChecked} from './to-be-partially-checked'
import {toHaveDescription} from './to-have-description'
import {toHaveErrorMessage} from './to-have-errormessage'
import {toHaveSelection} from './to-have-selection'

export {
toBeInTheDOM,
Expand Down Expand Up @@ -50,4 +51,5 @@ export {
toBePartiallyChecked,
toHaveDescription,
toHaveErrorMessage,
toHaveSelection,
}
46 changes: 46 additions & 0 deletions src/to-have-selection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import isEqualWith from 'lodash/isEqualWith'
import {
checkHtmlElement,
compareArraysAsSet,
getMessage,
getSelection,
} from './utils'

export function toHaveSelection(htmlElement, expectedSelection) {
checkHtmlElement(htmlElement, toHaveSelection, this)

const receivedSelection = getSelection(htmlElement)
const expectsSelection = expectedSelection !== undefined

let expectedTypedSelection = expectedSelection
let receivedTypedSelection = receivedSelection
if (
expectedSelection == receivedSelection &&
expectedSelection !== receivedSelection
) {
expectedTypedSelection = `${expectedSelection} (${typeof expectedSelection})`
receivedTypedSelection = `${receivedSelection} (${typeof receivedSelection})`
}

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 ? expectedTypedSelection : '(any)',
'Received',
receivedTypedSelection,
)
},
}
}
56 changes: 56 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,61 @@ function toSentence(
)
}

function getSelection(element) {
pwolaq marked this conversation as resolved.
Show resolved Hide resolved
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 if (selection.containsNode(element, true)) {
// Element is partially selected
const range = element.ownerDocument.getSelection().getRangeAt(0)
const selectionStartsWithinElement =
element === range.startContainer || element.contains(range.startContainer)
const selectionEndsWithinElement =
element === range.endContainer || element.contains(range.endContainer)

selection.removeAllRanges()
temporaryRange.selectNodeContents(element)

if (selectionStartsWithinElement) {
temporaryRange.setStart(range.startContainer, range.startOffset)
} else if (selectionEndsWithinElement) {
temporaryRange.setEnd(range.endContainer, range.endOffset)
}
selection.addRange(temporaryRange)
}

const result = selection.toString()

selection.removeAllRanges()
selection.addRange(originalRange)

return result
}

export {
HtmlElementTypeError,
NodeTypeError,
Expand All @@ -242,4 +297,5 @@ export {
getSingleElementValue,
compareArraysAsSet,
toSentence,
getSelection,
}