Search code examples
reactjsjestjsenzymeantdrecompose

Testing a component whose child has a context


I am using the antd Checkbox component in my CheckboxWidget component, the component has a contextType defined:

static contextTypes: {
   checkboxGroup: any
}

I would like to test it using shallow rendering with enzyme, so I am using the withContext helper from recompose inside the beforeEach block:

describe('Simple Checkbox Widget', () => {
  beforeEach(() => {
    withContext({
      getChildContext: function () {
        return {checkboxGroup: null}
      },
      childContextTypes: {
        checkboxGroup: shape({
          disabled: bool,
          toggleOption: func,
          value: array
        })
      }
    })(CheckboxWidget)
  })
})

However, when I write my test like this:

it('renders a checkbox from Antd', () => {
  const wrapper = shallow(<Subject />)
  const actual = wrapper.find(AntdCheckbox).length
  const expected = 1
  expect(actual).toEqual(expected)
})

I notice that the test is failing because it cannot find the Checkbox widget. I think it is because the rendered component will look like:

 <Subject />

I found that the wrapper.instance() is Subject and wrapper.instance().children is undefined. I tried to use wrapper.dive but it does not seem to be working on the wrapper.instance() either.


Solution

  • There is an easier way to put something in to the context. The shallow function accepts options as a second parameter. In the options you can pass the context for the component:

    it('renders a checkbox from Antd', () = > {
      const wrapper = shallow( < Subject / > , {
        context: {
          checkboxGroup: checkboxGroup: shape({
            disabled: bool,
            toggleOption: func,
            value: array
          })
        }
      })
      const actual = wrapper.find('AntdCheckbox').length
      const expected = 1
      expect(actual).toEqual(expected)
    })