Skip to content

Commit

Permalink
Fix a failed client-side test
Browse files Browse the repository at this point in the history
Using DOMPurify as in a guide produces an error because JEST do not have
access to window object, so I applied the solution linked below:
cure53/DOMPurify#29 (comment)
  • Loading branch information
timur987 committed Aug 16, 2023
1 parent f95a16f commit ae5d152
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions client/components/banner/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Button, Card, Gridicon } from '@automattic/components';
import { isMobile } from '@automattic/viewport';
import classNames from 'classnames';
import DOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';
import { size } from 'lodash';
import PropTypes from 'prop-types';
import { Component } from 'react';
Expand Down Expand Up @@ -182,6 +183,16 @@ export class Banner extends Component {
);
}

sanitize( html ) {
// Getting an instance of DOMPurify this way is needed to fix a related JEST test.
const { window } = new JSDOM( '<!DOCTYPE html>' );
const domPurify = DOMPurify( window );
return domPurify.sanitize( html, {
ALLOWED_TAGS: [ 'a' ],
ALLOWED_ATTR: [ 'href', 'target' ],
} );
}

getContent() {
const {
callToAction,
Expand All @@ -203,11 +214,6 @@ export class Banner extends Component {

const prices = Array.isArray( price ) ? price : [ price ];

const sanitizedDescription = DOMPurify.sanitize( description, {
ALLOWED_TAGS: [ 'a' ],
ALLOWED_ATTR: [ 'href', 'target' ],
} );

return (
<div className="banner__content">
{ tracksImpressionName && event && (
Expand All @@ -226,7 +232,7 @@ export class Banner extends Component {
{ description && (
<div
className="banner__description"
dangerouslySetInnerHTML={ { __html: sanitizedDescription } } // eslint-disable-line react/no-danger
dangerouslySetInnerHTML={ { __html: this.sanitize( description ) } } // eslint-disable-line react/no-danger
></div>
) }
{ size( list ) > 0 && (
Expand Down

0 comments on commit ae5d152

Please sign in to comment.