Skip to content

Commit

Permalink
Add ability to test nested children in examples
Browse files Browse the repository at this point in the history
  • Loading branch information
NickColley committed Jul 30, 2018
1 parent 4bc92cd commit 050d790
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
22 changes: 14 additions & 8 deletions lib/jest-helpers.js
Expand Up @@ -15,23 +15,29 @@ nunjucks.configure(configPaths.components, {
})

/**
* Render a component's template for testing
* Render a component's macro for testing
* @param {string} componentName
* @param {string} params parameters that are used in the component template
* @returns {function} returns cheerio (jQuery) instance of the template for easy DOM querying
* @param {string} params parameters that are used in the component macro
* @param {any} children any child components or text, pass the children to the macro
* @returns {function} returns cheerio (jQuery) instance of the macro for easy DOM querying
*/
function render (componentName, params) {
function render (componentName, params, children = false) {
if (typeof params === 'undefined') {
throw new Error('Parameters passed to `render` should be an object but are undefined')
}

const macroName = componentNameToMacroName(componentName)
const macroParams = JSON.stringify(params, null, 2)

let macroString = `
{%- from "${componentName}/macro.njk" import ${macroName} -%}
{{- ${macroName}(${macroParams}) -}}
`
let macroString = `{%- from "${componentName}/macro.njk" import ${macroName} -%}`

// If we're nesting child components or text, pass the children to the macro
// using the 'caller' Nunjucks feature
if (children) {
macroString += `{%- call ${macroName}(${macroParams}) -%}${children}{%- endcall -%}`
} else {
macroString += `{{- ${macroName}(${macroParams}) -}}`
}

const output = nunjucks.renderString(macroString)
return cheerio.load(output)
Expand Down
6 changes: 6 additions & 0 deletions src/components/fieldset/template.test.js
Expand Up @@ -108,4 +108,10 @@ describe('fieldset', () => {
expect($component.attr('data-attribute')).toEqual('value')
expect($component.attr('data-another-attribute')).toEqual('another-value')
})

it('renders nested components using `call`', () => {
const $ = render('fieldset', {}, '<div class="app-nested-component"></div>')

expect($('.govuk-fieldset .app-nested-component').length).toBeTruthy()
})
})

0 comments on commit 050d790

Please sign in to comment.