javascriptreactjsjestjsreact-test-renderersnapshot-testing

How to render plain html code with react-test-renderer or other alternative libs?


react-test-renderer's to JSON function returns React structure instead of plain html code.

For example:

import "./styles.css";
import renderer from 'react-test-renderer'

const Test1 = () => <span>Hello World!</span>
const Test2 = () => <span dangerouslySetInnerHTML={{ __html: 'Hello World!' }} />

export default function App() {
  return (
    <div className="App">
      <ul>
        <li key='test1'>{JSON.stringify(renderer.create(<Test1 />).toJSON())}</li>
        <li key='test2'>{JSON.stringify(renderer.create(<Test2 />).toJSON())}</li>
      </ul>
    </div>
  );
}

outputs:

{"type":"span","props":{},"children":["Hello World!"]}
{"type":"span","props":{"dangerouslySetInnerHTML":{"__html":"Hello World!"}},"children":null}

So if I change my code from Test1 to Test2, the snapshot tests failed.

But actually they generate the same html structure in browser.

I wonder if there's a method can render plain html code instead of react structure. for example:

<span>Hello World!</span>

codesandbox: https://codesandbox.io/s/brave-curie-lnt6y?file=/src/App.js:0-472


Solution

  • I figured it out with Estus Flask's help.

    import { render } from '@testing-library/react'
    
    render(<Test1 />).baseElement