var copyButton = document.querySelector('[data-component="copypaste-button"]');
var copyPasteText = document.querySelector('[data-component="copypaste-text"]');
function selectElementContents(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
console.log(range);
}
export function copyText() {
selectElementContents(copyPasteText);
document.execCommand('copy');
document.querySelector('.c-copypaste__button svg').classList.add('opacity1');
setTimeout(function() {
document.querySelector('.c-copypaste__button svg').classList.remove('opacity1');
}, 700);
}
copyButton.addEventListener('click', function() {
copyText();
copyButton.focus();
});
copyPasteText.addEventListener('click', copyText);
index.test.js
import copyText from '../js/index.js';
test('component copies the text', () => {
document.body.innerHTML =
`<button data-component="copypaste-button" value="copy"></button>
<div data-component="copypaste-text">My text</div>`;
// Emulate a click on our button
const copyButton = document.querySelector('[data-component="copypaste-button"]');
copyButton.click();
const {baseNode} = document.getSelection();
// Assert that the copyText function was called, and that the
// text was copied as we'd expect it to.
expect(copyText).toBeCalled();
expect(baseNode.nodeValue).toEqual('My text');
});
This is my first time writing a javascript test and using jest so the code might be total garbage
I don’t think you’re mocking up your test data correctly and I don’t think you can use document like this, from within a test itself. You should use setupFiles.