使用 Cypress 选择文本
Selecting text with Cypress
我正在尝试使用 Cypress 在 textarea
中 select 文本,但 运行 出现了一些问题。 Cypress api 没有我能找到的开箱即用的方法,所以我尝试自己实现它。
我找到了 this Whosebug answer about selecting text 并决定效仿它。我得出的结论是:
selectTextWithin = (selector: string) => {
cy.document().then((doc: Document) => {
cy.window().then((win: Window) => {
cy.get(selector).then((textElement: JQuery<HTMLElement>) => {
if (win.getSelection) {
const selection = win.getSelection();
const range = doc.createRange();
range.selectNodeContents(textElement.get(0));
selection.removeAllRanges();
selection.addRange(range);
} else {
throw new Error("Can't select text.")
}
})
})
})
}
它执行没有错误,但它似乎没有 selecting 任何文本。
您链接到的答案涉及专门在输入字段外选择文本。 Here 是在输入字段中选择文本的答案。
他们发布了 demo,我已经为 Cypress 修改了它。
HTML:
<html>
<body>
<textarea type="textarea" name="message" id="message">Hello World</textarea>
</body>
</html>
赛普拉斯:
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
field.focus();
}
describe('Text selection', function() {
it('Selects text in a text area', function() {
cy.get("#message").then(textarea => {
createSelection(textarea, 0, 5);
});
}
}
我正在尝试使用 Cypress 在 textarea
中 select 文本,但 运行 出现了一些问题。 Cypress api 没有我能找到的开箱即用的方法,所以我尝试自己实现它。
我找到了 this Whosebug answer about selecting text 并决定效仿它。我得出的结论是:
selectTextWithin = (selector: string) => {
cy.document().then((doc: Document) => {
cy.window().then((win: Window) => {
cy.get(selector).then((textElement: JQuery<HTMLElement>) => {
if (win.getSelection) {
const selection = win.getSelection();
const range = doc.createRange();
range.selectNodeContents(textElement.get(0));
selection.removeAllRanges();
selection.addRange(range);
} else {
throw new Error("Can't select text.")
}
})
})
})
}
它执行没有错误,但它似乎没有 selecting 任何文本。
您链接到的答案涉及专门在输入字段外选择文本。 Here 是在输入字段中选择文本的答案。
他们发布了 demo,我已经为 Cypress 修改了它。
HTML:
<html>
<body>
<textarea type="textarea" name="message" id="message">Hello World</textarea>
</body>
</html>
赛普拉斯:
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
field.focus();
}
describe('Text selection', function() {
it('Selects text in a text area', function() {
cy.get("#message").then(textarea => {
createSelection(textarea, 0, 5);
});
}
}