如何使用酶标仪找到嵌套的连接组件?

时间:2019-05-08 12:03:14

标签: reactjs jestjs enzyme

我有一个已连接的React Login组件:

class Login extends React.Component<ComponentProps, ComponentState> {

  public constructor(props: ComponentProps) {
    super(props);

    this.state = {
      username: '',
      password: '',
    };
  }
  ...
}

export default connect(
  null,
  mapDispatchToProps,
)(withRouter(withStyles(styles)(Login)));

我想测试在用户输入其凭据时状态是否已正确填充:

import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import { mount, ReactWrapper } from 'enzyme';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import { state } from 'tests/fixtures';
import Login, { ComponentState } from './Login';

const mockStore = configureStore();
const store = mockStore(state);

let wrapper: ReactWrapper<any, Readonly<{}>, React.Component<{}, {}, any>>;

beforeEach(() => {
  wrapper = mount(<Provider store={store}><Router><Login /></Router></Provider>);
});

it('should populate the state with credentials', () => {
  const loginInstance = wrapper.find('* > * > * > * > * > * > * > Login').instance();

  const inputUsername = wrapper.find('.testUsername input');
  inputUsername.simulate('change', { target: { value: 'someusername' } });
  expect((loginInstance.state as ComponentState).username).toEqual('someusername');

  const inputPassword = wrapper.find('.testPassword input');
  inputPassword.simulate('change', { target: { value: 'mySecretPassword' } });
  expect((loginInstance.state as ComponentState).password).toEqual('mySecretPassword');
});

wrapper.debug()如下:

<Provider store={{...}}>
  <BrowserRouter>
    <Router history={{...}}>
      <ConnectFunction>
        <withRouter(WithStyles(Login)) dispatchLogin={[Function: dispatchLogin]}>
          <Route>
            <WithStyles(Login) dispatchLogin={[Function: dispatchLogin]} history={{...}} location={{...}} match={{...}} staticContext={[undefined]}>
              <Login...

测试通过了,但是我想改进我的组件查找方法。 我尝试了酶文档上显示的wrapper.find(Login),但未找到组件。可以找到它的唯一方法是如上所述。 https://airbnb.io/enzyme/docs/api/ReactWrapper/find.html

如何找到带有酶固定物的连接组件?

1 个答案:

答案 0 :(得分:0)

“登录”是我连接的组件,但应该是您的组件(未连接),如:

export class Login extends React.Component<ComponentProps, ComponentState> {
  ...
}

因此您的测试将如下所示:

// Import the connected components (to mount) and the component
import ConnectedLogin, { Login } from './Login';

// Wrap the connected component
const wrapper = mount(<Provider store={store}><Router><ConnectedLogin /></Router></Provider>);

// Find the component that is NOT connected
const loginInstance = wrapper.find(Login).instance();