Skip to content

Commit

Permalink
Merge pull request #5251 from alphagov/create-all-check
Browse files Browse the repository at this point in the history
Add `isSupported` to `createAll`
  • Loading branch information
patrickpatrickpatrick authored Aug 20, 2024
2 parents f6c4859 + 3301745 commit 69763be
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
20 changes: 19 additions & 1 deletion packages/govuk-frontend/src/govuk/init.jsdom.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,12 @@ describe('initAll', () => {
})

describe('createAll', () => {
beforeEach(() => {
document.body.classList.add('govuk-frontend-supported')
})

afterEach(() => {
document.body.innerHTML = ''
document.body.outerHTML = '<body></body>'
})

class MockComponent {
Expand Down Expand Up @@ -176,6 +180,20 @@ describe('createAll', () => {
expect(result).toStrictEqual([])
})

it('throws error and returns empty array if not supported', () => {
document.body.classList.remove('govuk-frontend-supported')

const result = createAll(MockComponent)

expect(global.console.log).toHaveBeenCalledWith(
expect.objectContaining({
message: 'GOV.UK Frontend is not supported in this browser'
})
)

expect(result).toStrictEqual([])
})

it('returns an empty array if no matching components exist on the page', () => {
const componentRoot = document.createElement('div')
componentRoot.setAttribute(
Expand Down
6 changes: 6 additions & 0 deletions packages/govuk-frontend/src/govuk/init.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ function createAll(Component, config, $scope = document) {
`[data-module="${Component.moduleName}"]`
)

// Skip initialisation when GOV.UK Frontend is not supported
if (!isSupported()) {
console.log(new SupportError())
return []
}

/* eslint-disable-next-line @typescript-eslint/no-unsafe-return --
* We can't define CompatibleClass as `{new(): CompatibleClass, moduleName: string}`,
* as when doing `typeof Accordion` (or any component), TypeScript doesn't seem
Expand Down

0 comments on commit 69763be

Please sign in to comment.