I have a React Login, connected component:
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)));
I would like to test that the state is populated properly as the user enters his credentials:
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() looks as follow:
<Provider store={{...}}>
<BrowserRouter>
<Router history={{...}}>
<ConnectFunction>
<withRouter(WithStyles(Login)) dispatchLogin={[Function: dispatchLogin]}>
<Route>
<WithStyles(Login) dispatchLogin={[Function: dispatchLogin]} history={{...}} location={{...}} match={{...}} staticContext={[undefined]}>
<Login...
The tests are passing, but I would like to improve my component finding method. I tried wrapper.find(Login) as shown on the enzyme doc, but the Component is not found. The only way it can be found is doing it as shown above. https://airbnb.io/enzyme/docs/api/ReactWrapper/find.html
How can I find connected components with enzyme mount?
state
of theLogin
component, why don't you export theLogin
component (with named export) :export class Login extends React
and test it outside ofreact-redux
,react-router
etc.. You just need toimport {Login} from './Login';
in your test – Olivier Boissé