我正在努力解决测试问题。我已经构建了一个 react/next/apollo 应用程序,并且我试图编写我认为是基本测试的东西,但我无法让它工作。我收到以下错误:
TypeError: Cannot read property 'data' of undefined
85 | constructor(props) {
86 | super(props)
> 87 | this.apollo = initApollo(props.stateApollo.apollo.data)
88 | this.redux = initRedux(props.stateRedux)
89 | }
90 |
at new WithData (lib/withData.js:87:73)
at ReactShallowRenderer.render (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:92:26)
at node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:287:35
at withSetStateAllowed (node_modules/enzyme-adapter-utils/build/Utils.js:94:16)
at Object.render (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:286:68)
at new ShallowWrapper (node_modules/enzyme/build/ShallowWrapper.js:119:22)
at shallow (node_modules/enzyme/build/shallow.js:19:10)
at Object.<anonymous> (__tests__/pages/index.test.js:14:35)
经过半天的谷歌搜索,这里似乎有两个可能的问题。
1) apollo 使用的 'withData' HOC 导致浅渲染器失败。
2)我错过了某种嘲笑(我不完全理解)
烦人的是我不关心数据。我要做的就是检查页面是否加载了正确的组件。
这是我正在测试的页面:
// Import global 'app' component
import App from 'components/app'
// Next JS Universal Rendering toolkit
import Head from 'next/head'
// Connect to Apollo and provide data to app
import withData from 'lib/withData'
export default withData(props =>
<App>
<Head>
{/* All meta information for a page should go in this component */}
<title> Top 10 VPN </title>
</Head>
<p>Hello World!</p>
</App>
)
这是我的测试脚本:
import { shallow } from 'enzyme'
import React from 'react'
import renderer from 'react-test-renderer'
import Page from '../../pages/index.js'
describe('Index Page', () => {
it('App is defined"', () => {
const app = shallow(<Page stateApollo={{}} stateRedux={{}} />)
expect(app.find('<Head>').exists()).to.equal(true)
expect(app.find('<p>').exists()).to.equal(true)
})
})