From 0e7b529fbc88e8365fd6067e1c3215b901874cdc Mon Sep 17 00:00:00 2001 From: Tom Byers Date: Mon, 12 Aug 2019 10:19:34 +0100 Subject: [PATCH] Add mock helpers for Range and Selection To add the text from an element to the clipboard you need to: 1. get the current Selection 1. create a Range from the contents of the element 2. clear any existing Ranges from the Selection and add the new Range to the selection 3. execute the 'copy' command To track calls to all the DOM APIs involved in this we need mocks for Range and Selection. Range: https://developer.mozilla.org/en-US/docs/Web/API/Range Selection: https://developer.mozilla.org/en-US/docs/Web/API/Selection Also includes a base class to help building out Web API interface mocks. --- tests/javascripts/support/helpers.js | 46 ++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/tests/javascripts/support/helpers.js b/tests/javascripts/support/helpers.js index 9e7b056a8..ee56ae375 100644 --- a/tests/javascripts/support/helpers.js +++ b/tests/javascripts/support/helpers.js @@ -227,6 +227,50 @@ class WindowMock { } } +// Base class for mocking an DOM APi interfaces not in JSDOM +class DOMInterfaceMock { + + constructor (jest, spec) { + + // set up methods so their calls can be tracked + // leave implementation/return values to the test + spec.methods.forEach(method => this[method] = jest.fn(() => {})); + + // set up props + // any spies should be relative to the test so not set here + spec.props.forEach(prop => { + + Object.defineProperty(this, prop, { + get: () => this[prop], + set: value => this[prop] = value + }); + + }); + + } + +} + +// Very basic class for stubbing the Range interface +// Only contains methods required for current tests +class RangeMock extends DOMInterfaceMock { + + constructor (jest) { + super(jest, { props: [], methods: ['selectNodeContents'] }); + } + +} + +// Very basic class for stubbing the Selection interface +// Only contains methods required for current tests +class SelectionMock extends DOMInterfaceMock { + + constructor (jest) { + super(jest, { props: [], methods: ['removeAllRanges', 'addRange'] }); + } + +} + // function to ask certain questions of a DOM Element const element = function (el) { return new ElementQuery(el); @@ -236,5 +280,7 @@ exports.triggerEvent = triggerEvent; exports.clickElementWithMouse = clickElementWithMouse; exports.moveSelectionToRadio = moveSelectionToRadio; exports.activateRadioWithSpace = activateRadioWithSpace; +exports.RangeMock = RangeMock; +exports.SelectionMock = SelectionMock; exports.element = element; exports.WindowMock = WindowMock;