在用Jest和Enzyme编写的测试用例中,道具没有通过组件内部

时间:2018-10-29 12:53:52

标签: reactjs jestjs enzyme

这是我的测试用例

import React from 'react';
import { mount } from 'enzyme';
import CustomForm from '../index';

describe('Custom Form mount testing', () => {
  let props;
  let mountedCustomForm;
  beforeEach(() => {
    props = {
      nav_module_id: 'null',
    };
    mountedCustomForm = undefined;
  });

  const customform = () => {
    if (!mountedCustomForm) {
      mountedCustomForm = mount(
        <CustomForm {...props} />
    );
    }
    return mountedCustomForm;
  };

  it('always renders a div', () => {
    const divs = customform().find('div');
    console.log(divs);
  });
});

每当我使用yarn test运行测试用例时。它给出了以下错误TypeError: Cannot read property 'nav_module_id' of undefined

我已经在多个地方放置了控制台,以查看道具的价值。它正在设置。但是它不能仅仅通过组件并给出上面提到的错误。

任何帮助都将被困近2-3天,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

您必须将要测试的组件包装在beforeEach方法中,以使其可用于所有“ it”块,并且还必须使用您认为已进入原始组件的模拟道具。

import React from 'react'
import {expect} from 'chai'
import {shallow} from 'enzyme'
import sinon from 'sinon'
import {Map} from 'immutable'
import {ClusterToggle} from '../../../src/MapView/components/ClusterToggle'

describe('component tests for ClusterToggle', () => {

let dummydata

  let wrapper

  let props

  beforeEach(() => {

    dummydata = {
      showClusters: true,
      toggleClustering: () => {}
    }

    wrapper = shallow(<ClusterToggle {...dummydata} />)

    props = wrapper.props()

  })

  describe(`ClusterToggle component tests`, () => {

    it(`1. makes sure that component exists`, () => {
      expect(wrapper).to.exist
    })

    it('2. makes sure that cluster toggle comp has input and label', () => {
      expect(wrapper.find('input').length).to.eql(1)
      expect(wrapper.find('label').length).to.eql(1)
    })

    it('3. simulating onChange for the input element', () => {
      const spy = sinon.spy()
      const hct = sinon.spy()
      hct(wrapper.props(), 'toggleClustering')
      spy(wrapper.instance(), 'handleClusterToggle')
      wrapper.find('input').simulate('change')
      expect(spy.calledOnce).to.eql(true)
      expect(hct.calledOnce).to.eql(true)
    })
  })
})