【问题标题】:Issue with accessing the state and method in jest开玩笑地访问状态和方法的问题
【发布时间】:2018-12-26 11:53:41
【问题描述】:

我一直在 React 和 HOC 中使用 jest 进行单元测试。目前,我在访问班级的状态和方法时遇到问题。查看下面的示例代码

//Login.Container.js

import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
class Login extends Component {
    constructor(props) {
       super(props);
       this.state = {
          isShowLoader: false,
       };
       this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit() {
       //sample code
    }

    render() {
       return (
           <LoginComponent />
       );
    }

    function mapStateToProps(state) {
        return {
             task: state
        };
    }  

    function mapDispatchToProps(dispatch) {
        return bindActionCreators(
             Object.assign({},
                 actions),
                 dispatch);
    }

    export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Login));

    Login.displayName = 'Login';

登录组件示例

    //Login.Component.js

    const LoginComponent = props => {
         return (<div>hi</div>);
    }

我使用 jest 和酶的示例测试套件

 //login.test.js
import { Provider } from 'react-redux';
import { history, store} from '../store';
import { ConnectedRouter } from 'react-router-redux';
describe('>>>Login --- Container', () => {       
let wrapperInner
it('should perform login container by using ComponentWapper', async () => {      
    wrapperInner = mount(<Provider store={store}>
                              <ConnectedRouter history={history}>
                                    <Login />
                              </ConnectedRouter>
                          </Provider>);       

    const instance = wrapperInner.instance();
    expect(wrapperInner.state('isShowLoader')).toBe(true);
    const responseJson = await instance.handleSubmit();       
});
}); 

【问题讨论】:

    标签: reactjs react-redux jestjs enzyme higher-order-components


    【解决方案1】:

    终于找到了解决这个问题的办法。

       wrapperInner.find("Login").instance() // to access the methods
    
       wrapperInner.find("Login").instance().state // to access the state
    

    更多详情请查看:https://github.com/airbnb/enzyme/issues/361

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 2020-03-25
      • 1970-01-01
      • 2022-08-20
      • 2019-03-23
      • 1970-01-01
      • 2021-12-10
      • 2021-04-09
      相关资源
      最近更新 更多