0

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.

vamsiampolu
  • 6,328
  • 19
  • 82
  • 183

1 Answers1

1

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)
})
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • I converted my tests using `mount(, mountOptions)` to `shallow(, shallowOptions)` with shallowOptions being the options you provided. Thank you – vamsiampolu Jun 14 '17 at 00:27