ReactJS / JestJS / Enzyme:如何测试compose()中使用的graphql()函数?

问题描述 投票:1回答:1

这就是我通过jestJS使用react-apollo测试一个非常简单的reactJS组件的方法。我也在使用jest的覆盖功能。

但覆盖范围告诉我,我缺少测试options: (props) => ({中的graphql()线。

我该怎么做才能正确?

Example.js

import React, { Component } from 'react'
import { graphql, compose } from 'react-apollo'
import { getPostsQuery } from './graphql/query'

export class Example extends Component {
  render () {
    const { data } = this.props
    const { getPosts, loading } = data

    return (
      <div id="article">
        {
          getPosts.map(post => {
            return (<div>{post.content}</div>)
          })
        }
      </div>
    )
  }
}

export default compose(
  graphql(
    getPostsQuery, {
      options: (props) => ({
        variables: {
          articleId: props.articleId
        }
      })
    }
  )
)(Example)

单元测试

import React from 'react'
import { shallow } from 'enzyme'
import { Example } from './components/Example'

describe('<Example />', () => {
  it('should render #article element', () => {
    wrapper = shallow(<Example data={data} />)
    expect(wrapper.find('#article')).toHaveLength(1)
  })
})
javascript reactjs unit-testing jestjs react-apollo
1个回答
0
投票

据我所知,你的测试没有测试阿波罗比特。现在你正在测试React是否能够渲染div。这是因为您只导入组件而不是它的增强版本。如果你想覆盖所有你需要的import Example from './components/Example'。但是你会有另外一个关于模拟apollo服务器的问题。这是一篇关于https://medium.com/@carlos_42328/mocking-api-responses-with-react-apollo-11eb4610debe主题的好文章

另一个选择是使用Jest的coveragePathIgnorePatterns选项,如下所示:

Example.js

import React, { Component } from 'react'
import { graphql, compose } from 'react-apollo'
import { getPostsQuery } from './graphql/query'

export default class Example extends Component {
  render () {
    const { data } = this.props
    const { getPosts, loading } = data

    return (
      <div id="article">
        {
          getPosts.map(post => {
            return (<div>{post.content}</div>)
          })
        }
      </div>
    )
  }
}

ExampleComposed.js

import Example from './Example';

export default compose(
  graphql(
    getPostsQuery, {
      options: (props) => ({
        variables: {
          articleId: props.articleId
        }
      })
    }
  )
)(Example)

然后在你的package.json文件中

{
  "jest": {
    "coveragePathIgnorePatterns": [
      "./node_modules",
      "./path/to/file/ExampleComposed.js"
    ]
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.