Как бы я заглушки с помощью sinon, getElementsByClassName, чтобы вернуть узел div с определенным className и innerHTML? - PullRequest
0 голосов
/ 12 апреля 2019

как бы заглушить, используя sinon, "document.getElementsByClassName", чтобы вернуть узел div с определенным именем класса и innerHTML. Ниже приведен код, где я пытаюсь выполнить модульное тестирование.

handleCopyToClipboard(){
var range = document.createRange();
            range.selectNodeContents(document.getElementsByClassName('copy-text')[0]);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
            document.execCommand("copy");
            window.getSelection().removeAllRanges();
}

1 Ответ

0 голосов
/ 12 апреля 2019
            let selectionNode = null;
            const selectNodeContents = (node) =>  {
                selectionNode = node;
            };
            sinon.stub(document, "createRange", () => {
                return {
                    selectNodeContents
                };
            });
            sinon.stub(window, "getSelection", () => {
                return {
                    removeAllRanges() {
                    },
                    addRange() {
                    }
                };
            });
            const textToCopy = "test text";
            const copyCommand = sinon.stub(document, "execCommand");
            const getElementsStub = sinon.stub(document, "getElementsByClassName");
            const fakeDiv = {
                innerHTML: textToCopy
            };
            getElementsStub.withArgs("copy-text").returns([fakeDiv]);
            handleCopyToClipboard(); //call the above function to test
            expect(copyCommand.calledWith("copy")).to.be.true;
            expect(selectionNode.innerHTML).to.equal(textToCopy);
...