不变违规:尝试使用Jest / Enzyme测试React组件时,元素类型无效错误

时间:2019-02-26 14:23:59

标签: javascript reactjs jestjs enzyme

我在其他地方发现了这些问题,但情况与我本人不太一样,因此努力寻找解决问题的方法。就我而言,该组件可以正常工作,但是在尝试安装它时出现此错误:

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `RepoDropdown`.

我想挂载它,以便可以测试已创建的选择组件的onChange部分。该组件如下所示:

const SelectRepo = styled.select`
  // CSS rules here
`;

export class RepoDropdown extends PureComponent {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    // Logic here
  }

  render() {
    if (!this.props.repoList) {
      return null;
    }

    const repoItems = this.props.repoList.map(repo => (
      <RepoDropdownItem repo={repo.name} key={repo.id} />
    ));

    return (
      <SelectRepo onChange={this.handleChange}>
        {repoItems}
      </SelectRepo>
    );
  }
}

RepoDropdown.propTypes = {
  // Required propTypes here
};

export const mapStateToProps = state => ({
  repoList: getAllRepos(state),
});

export default connect(
  mapStateToProps,
  { getRepoInfo, updateCurrentUrl, updateWrongRepo }
)(RepoDropdown);

这是我尝试安装组件的方式:

it('SHOULD call onChange function when new repo is selected', () => {
  const middlewares = [thunk];
  const mockStore = configureStore(middlewares);
  const initialState = {
    repos: {
      repoList: [{ name: 'sample1', id: 1 }, { name: 'sample2', id: 2 }],
    },
  };
  const store = mockStore(initialState);

  const component = mount(
    <DefaultThemeProvider>
      <Provider store={store}>
        <RepoDropdown
          getRepoInfo={getRepoInfo}
          repoList={[
            { name: 'the-value', id: 1 },
            { name: 'not-the-value', id: 2 },
          ]}
          updateCurrentUrl={updateCurrentUrl}
          updateWrongRepo={updateWrongRepo}
        />       
      </Provider>
    </DefaultThemeProvider>
  );

  component
    .find('select')
    .simulate('change', { target: { value: 'sample1' } });
  expect(component.find('select').prop('onChange')).toHaveBeenCalled();
});

我尝试了各种进出口方式来尝试解决此问题,因为这在其他地方已提出,但无济于事。我觉得这与正在渲染的子组件有关,但无法找到解决方法。

0 个答案:

没有答案