Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render ReactMarkdown using react-testing-library?

I have a rather simple "markdown formatter" in my code. It gets a string and returns a ReactNode:

export const markdownFormatter = (cellData: string): React.ReactNode => {
  try {
    return (
      <ReactMarkdown remarkPlugins={[remarkGfm]}>{cellData}</ReactMarkdown>
    );
  } catch (error) {
    console.error(error);
    return <>{"Something went wrong when displaying this content."}</>;
  }
};

I'm trying to test it using react-testing-library like this:

  test(`pass markdown content | expect it to be rendered as markdown`, () => {
    const text = 'This is a **markdown** text';
    const { container } = render(
      <div>{markdownFormatter('this is some **markdown** text!')}</div>,
    );
    expect(container.firstChild).toContainHTML(
      'This is a <strong>markdown</strong> text',
    );
  });

But for some reason, the content ISN'T rendered as Markdown in the container:

Expected:
  this is some <strong>markdown</strong> text!
Received:
  <div>this is some **markdown** text!</div>

I checked and the formatter does work when just adding it to a page, so something is wrong with the test (or the render).

Here's how I'm using it in my app (literally the same):

<div>
    {markdownFormatter('this is some **markdown** text!')}
</div>

Resulting with this HTML (rendered and inspected):

screenshot of the markdown working

screenshot of the HTML code working

like image 248
Shay Nehmad Avatar asked May 20 '26 22:05

Shay Nehmad


1 Answers

this comment from React Markdown issues actually helped me with this:

https://github.com/remarkjs/react-markdown/issues/635#issuecomment-956158474

create a folder on "src" called "mocks" and inside the mocks folder a file called "react-markdown.js" with this code:

// src/__mocks__/react-markdown.js
function ReactMarkdown({ children }){
  return <>{children}</>
}

export default ReactMarkdown

on test file i made this:

const post: PostProps = {
  markdownBody: '## Testing markdown - test - markdown',
  slug: 'test-markdown',
}

describe('Post module', () => {
  test('it should render markdown', async () => {
    render(<Post postContent={post.markdownBody} />)
    const postSection = screen.getByTestId('post-section')

    expect(postSection).toHaveTextContent(post.markdownBody)
  })
})

unfortunately when u mock, you lose the ability to test the markdown lib.

another thing to keep in mind is with that you receive a string like the "markdownBody" in test, not the html structure. you can see this using "debug()":

const { debug } = render(<Post postContent={post.markdownBody} />)
debug()

hope it helps!

like image 136
Raniel César Avatar answered May 23 '26 11:05

Raniel César



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!