【发布时间】:2019-09-26 03:59:26
【问题描述】:
我有一个 React 登录,连接组件:
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
如何使用酶安装找到连接的组件?
【问题讨论】:
-
如果您只想测试
Login组件的state,为什么不导出Login组件(带有命名导出):export class Login extends React并在外部测试它react-redux,react-router等等。你只需要在你的测试中import {Login} from './Login'; -
我为其他一些测试做了这个。在这种情况下,我正在处理文本字段(Material UI 组件)并且需要渲染它们。这不适用于浅包装,有什么提示吗?谢谢!