简体   繁体   中英

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

This is how I'm testing a very simple reactJS component with react-apollo via jestJS. I'm also using the coverage function of jest.

But the coverage shows me, that I'm missing to test the line options: (props) => ({ in the graphql() .

How should I do this correctly?

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)

Unit test

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)
  })
})

As far as I can see your test does not test the apollo bit right. Right now you are testing if React is able to render a div. That is because you are importing the component only and not the enhanced version of it. If you wanna cover everything you have to import Example from './components/Example' . But then you'll have another problem about mocking the apollo server. Here is a good article on that topic https://medium.com/@carlos_42328/mocking-api-responses-with-react-apollo-11eb4610debe

Another option is to use Jest's coveragePathIgnorePatterns option like so:

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)

And then in your package.json file

{
  "jest": {
    "coveragePathIgnorePatterns": [
      "./node_modules",
      "./path/to/file/ExampleComposed.js"
    ]
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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