Skip to content

Commit

Permalink
Rewrite test checking the closestAttributeValue reads up the DOM tree
Browse files Browse the repository at this point in the history
Make the HTML structure more apparent than creating a series of elements manually
  • Loading branch information
romaricpascal committed Oct 3, 2022
1 parent 2e66ec9 commit 44bfc76
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
14 changes: 14 additions & 0 deletions lib/dom-helpers.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,17 @@ export function createElement (tagName, attributes = {}) {

return el
}

/**
* Creates a DocumentFragment from the given HTML
*
* Allows to quickly scaffold parts of a DOM tree for testing
*
* @param {String} html - The HTML to turn into a DOM tree
* @returns DocumentFragment
*/
export function createFragmentFromHTML (html) {
const template = document.createElement('template')
template.innerHTML = html
return template.content.cloneNode(true)
}
19 changes: 11 additions & 8 deletions src/govuk/common.unit.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @jest-environment jsdom
*/

import { createElement } from '../../lib/dom-helpers.mjs'
import { createElement, createFragmentFromHTML } from '../../lib/dom-helpers.mjs'
import { mergeConfigs, extractConfigByNamespace, normaliseString, normaliseDataset, closestAttributeValue } from './common.mjs'

// TODO: Write unit tests for `nodeListForEach` and `generateUniqueID`
Expand Down Expand Up @@ -226,13 +226,16 @@ describe('Common JS utilities', () => {
})

it('returns the value of the closest parent with the attribute if it exists', () => {
const $greatGrandParent = createElement('div', { lang: 'cy-GB' }) // To check that we take the value up
const $grandparent = createElement('div', { lang: 'en-GB' })
const $parent = createElement('div') // To check that we walk up the tree
const $element = createElement('div')
$greatGrandParent.appendChild($grandparent)
$grandparent.appendChild($parent)
$parent.appendChild($element)
const dom = createFragmentFromHTML(`
<div lang="cy-GB"><!-- To check that we take the first value up -->
<div lang="en-GB"><!-- The value we should get -->
<div><!-- To check that we walk up the tree -->
<div class="target"></div>
</div>
</div>
</div>
`)
const $element = dom.querySelector('.target')

expect(closestAttributeValue($element, 'lang')).toEqual('en-GB')
})
Expand Down

0 comments on commit 44bfc76

Please sign in to comment.