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.