繁体   English   中英

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

[英]ReactJS/JestJS/Enzyme: How to test graphql() function used in compose()?

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

但是覆盖范围告诉我,我缺少测试行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)
  })
})

据我所知,您的测试未正确测试阿波罗位。 现在,您正在测试React是否能够渲染div。 这是因为您仅导入组件,而不是增强版本。 如果您想涵盖所有内容,则必须import Example from './components/Example' 但是随后您将遇到另一个关于模拟阿波罗服务器的问题。 这是一篇关于该主题的好文章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"
    ]
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM