LoginSignup
2
1

More than 5 years have passed since last update.

`next/head` で定義した<head>タグの中身をテストする

Posted at

Next.jsのpagesコンポーネント以下で、next/head で定義した

タグの中身をテストしたかった。

HeadはReact.Componentなのでenzymeでmountしてjestでテストをした。
next.js/head.js · zeit/next.js

対象のコンポーネント

import React from "react"
import Head from 'next/head'

const App = () => (
    <Head>
        <title>阿部寛のホームページ</title>
    </Head>
)

export default class Page extends React.Component {
  render() {
      <App />
  }
}

テストコード

import {mount} from 'enzyme';
import Page from './index'

describe('page /', () => {
  it('title in html header', ()=> {
    const component = mount(<Page />)
    const head = component.find('Head')

    const title = head.props()
        .children
        .find(el => el.type === 'title')
        .props
        .children

    expect(title).toEqual('阿部寛のホームページ')
  })
})

mount() して find() するとReactコンポーネントが手に入るので、素直にpropsを辿る。

コンポーネントを辿らなくていい場合は Shallow Rendering で対象を浅く参照すればよくて、
今回の場合奥からtitleを引っ張り出さないといけないので mount() が良いらしい。

Static Rendering でもよさそうなんだけど <Head> 中身を取得できなかったため mount() にした。理屈はわからない。

実行

$ jest
 PASS  src/app/pages/index.test.js
  page /
    ✓ title in html header (62ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.894s
Ran all test suites matching /index.test.js/i.
2
1
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
2
1