LoginSignup
4
2

More than 5 years have passed since last update.

React コンポーネントのレンダリング結果をテストする

Posted at

enzyme を使うと具体的な HTML を気にせず、あるコンポーネントが含まれているかなどを検証する変更に強いテストが書けます。一方で、テストが通らない時などには実際にどういう HTML が出力されるかがわかると便利です。

enzyme でのテストと HTML 文字列でのテストは次のように書くことができます。

import React from "react"
import Markdown from "./Markdown"
import { shallow } from "enzyme"
import { renderToStaticMarkup } from "react-dom/server"

describe("Markdown", () => {

  // HTML文字列でテスト
  it("should renders headers", () => {
    const html = renderToStaticMarkup(<Markdown markdown="# hello" />)
    expect(html).toEqual(`<div class="Markdown"><div><h1>hello</h1></div></div>`)
  })

  // enzyme でテスト
  it("should renders emphasis", () => {
    const wrapper = shallow(<Markdown markdown="*bold*" />)
    expect(wrapper.contains(<em>bold</em>)).toEqual(true)
  })
})
4
2
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
4
2