1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React Jest】DOMPurifyを自動テスト中に使った際のimportエラー

Posted at

はじめに

Reactの自動テストを行った際に、コンポーネント側でDOMPurifyをimportしてたのですが、読み込みエラーが出て困ったため記載します

問題

テスト対象のコンポーネントでDOMPurifyをimportしてところ以下エラーが発生

TypeError: Cannot read properties of undefined (reading 'sanitize')

      22 |       <Heading size='md' noOfLines={1}>自己紹介</Heading>
      23 |       <Text fontSize='sm' data-testid='description'>
    > 24 |         {parse(DOMPurify.sanitize(
         |                          ^
      25 |           user?.description || '', {
      26 |             ALLOWED_TAGS: ['img'],
      27 |             ALLOWED_ATTR: ['href', 'target', 'src']

コンポーネント側の記載

import DOMPurify from 'dompurify';

type UserInfoProps = {
  user: UserProfile,
  skills: userSkills[]
};

export const UserInfo = (props: UserInfoProps) => {
  const { user, skills } = props;

  return (
    <>
      <Heading size='md' noOfLines={1}>自己紹介</Heading>
      <Text fontSize='sm' data-testid='description'>
        {parse(DOMPurify.sanitize(
          user?.description || '', {
            ALLOWED_TAGS: ['img'],
            ALLOWED_ATTR: ['href', 'target', 'src']
          }
        ))}
      </Text>

解決方法

以下インポート文に書き換えて、ページ側の処理もテストの処理もうまくいくようになった

import * as DOMPurify from 'isomorphic-dompurify';

解決できなかったが途中行ったこと

以下インポート文に書き換えたらテストはうまくいったが、ページ側でエラーがでました。

import * as DOMPurify from 'dompurify';

でたエラー(webコンソール上)

Uncaught TypeError: DOMPurify.sanitize is not a function
    at UserInfo (user_info.tsx:24:26)
    at renderWithHooks (chunk-6VWAHX6D.js?v=9a0a9ad0:11548:26)
    at mountIndeterminateComponent (chunk-6VWAHX6D.js?v=9a0a9ad0:14926:21)
    at beginWork (chunk-6VWAHX6D.js?v=9a0a9ad0:15914:22)
    at beginWork$1 (chunk-6VWAHX6D.js?v=9a0a9ad0:19753:22)
    at performUnitOfWork (chunk-6VWAHX6D.js?v=9a0a9ad0:19198:20)
    at workLoopSync (chunk-6VWAHX6D.js?v=9a0a9ad0:19137:13)
    at renderRootSync (chunk-6VWAHX6D.js?v=9a0a9ad0:19116:15)
    at recoverFromConcurrentError (chunk-6VWAHX6D.js?v=9a0a9ad0:18736:28)
    at performConcurrentWorkOnRoot (chunk-6VWAHX6D.js?v=9a0a9ad0:18684:30)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?