Reactjs console.log(Wrapper.debug())显示<;ContextConsumer>;[功能]</ContextConsumer>;

Reactjs console.log(Wrapper.debug())显示<;ContextConsumer>;[功能]</ContextConsumer>;,reactjs,unit-testing,jestjs,enzyme,Reactjs,Unit Testing,Jestjs,Enzyme,我在react js中使用jest和Ezyme进行单元测试。 当我使用“console.log(wrapper.debug())”控制台记录浅层函数返回的包装器时,它返回[function],我无法在组件中找到属性 这是我的注册组件 signUp.js import React, { Component } from 'react' import { withStyles, Card, CardContent, Typography, MenuItem } from '@material-ui/

我在react js中使用jest和Ezyme进行单元测试。 当我使用“console.log(wrapper.debug())”控制台记录浅层函数返回的包装器时,它返回[function],我无法在组件中找到属性

这是我的注册组件

signUp.js

import React, { Component } from 'react'
import { withStyles, Card, CardContent, Typography, MenuItem } from '@material-ui/core';
import { darken } from '@material-ui/core/styles/colorManipulator';
import { FuseAnimate } from '@fuse';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux';
import { Link, withRouter } from 'react-router-dom';
import classNames from 'classnames';
import * as Actions from '../../../auth/store/actions/register.actions';
import * as FuseActions from '../../../store/actions/fuse/message.actions';
import Formsy from 'formsy-react';
import { TextFieldFormsy } from '@fuse';
import { Button, InputAdornment, Icon, Grid } from '@material-ui/core';


const styles = theme => ({
    root: {
        background: 'linear-gradient(to right, ' + theme.palette.primary.dark + ' 0%, ' + darken(theme.palette.primary.dark, 0.5) + ' 100%)',
        color: theme.palette.primary.contrastText
    }
});

class SignUp extends Component {

    render() {
        const { classes } = this.props;
        const { canSubmit } = this.state;

        return (
            <div data-test="data-component" className={classNames(classes.root, "flex flex-col flex-1 flex-no-shrink p-24 md:flex-row md:p-0")}>
               .........
            </div>
        )
    }
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        userSignup: Actions.userSignup,
        disableErrors: Actions.disableErrors,
        showMessage: FuseActions.showMessage
    }, dispatch);
}

function mapStateToProps({ auth }) {
    return {
        register: auth.register
    }
}


export default withStyles(styles, { withTheme: true })(withRouter(connect(mapStateToProps, mapDispatchToProps)(SignUp)));


import React,{Component}来自“React”
从“@material ui/core”导入{with styles,Card,CardContent,排版,MenuItem};
从“@material ui/core/styles/colorManipulator”导入{darken};
从'@fuse'导入{FuseAnimate};
从“react redux”导入{connect}
从“redux”导入{bindActionCreators};
从“react router dom”导入{Link,withRouter};
从“类名称”导入类名称;
将*作为操作从“../../../auth/store/Actions/register.Actions”导入;
从“../../../store/actions/fuse/message.actions”导入*作为FuseActions;
从“Formsy react”导入Formsy;
从'@fuse'导入{TextFieldFormsy};
从“@material ui/core”导入{按钮、输入设置、图标、网格};
常量样式=主题=>({
根目录:{
背景:“线性渐变(向右,”+theme.palette.primary.dark+'0%,“+darken(theme.palette.primary.dark,0.5)+'100%),
颜色:theme.palette.primary.ContractText
}
});
类注册扩展了组件{
render(){
const{classes}=this.props;
const{canSubmit}=this.state;
返回(
.........
)
}
}
功能图DispatchToprops(调度){
返回bindActionCreators({
userSignup:Actions.userSignup,
disableErrors:Actions.disableErrors,
showMessage:FuseActions.showMessage
},派遣);
}
函数MapStateTops({auth}){
返回{
寄存器:auth.register
}
}
使用样式导出默认值(样式,{withTheme:true})(使用路由器(连接(mapStateToProps,mapDispatchToProps)(注册));
这是测试文件

signUp.test.js

import React from 'react';

import { configure, shallow } from 'enzyme';

import Adapter from 'enzyme-adapter-react-16';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';

import SignUp from './signUp';
import AppContext from '../../../AppContext';

configure({ adapter: new Adapter() });

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

const setup = (initialState = {}) => {
    const store = mockStore(initialState);
    const wrapper = shallow(<SignUp store={store} />).dive().dive();
    console.log(wrapper.debug());

    return wrapper;
}

const findAttrByTest = (wrapper, val) => {
    return wrapper.find(`[data-test="${val}"]`);
}

describe("render <SignUp>", () => {
    let wrapper;
    beforeEach(() => {
        const initialState = {
            error: '',
            success: false
        };
        wrapper = setup(initialState);
    });
    test("render component without error", () => {
        const component = findAttrByTest(wrapper, 'data-component');
        expect(component.length).toBe(1);
    });
});
从“React”导入React;
从“酶”导入{configure,shallow};
从'enzyme-Adapter-react-16'导入适配器;
从“redux模拟存储”导入configureMockStore;
从“redux thunk”导入thunk;
从“./SignUp”导入注册;
从“../../../AppContext”导入AppContext;
配置({adapter:newadapter()});
const middleware=[thunk];
const mockStore=configureMockStore(中间件);
常量设置=(初始状态={})=>{
常量存储=模拟存储(初始状态);
const wrapper=shallow().dive().dive();
log(wrapper.debug());
返回包装器;
}
const findAttrByTest=(包装,val)=>{
返回wrapper.find(`[data test=“${val}”]`);
}
描述(“渲染”,()=>{
让包装纸;
在每个之前(()=>{
常量初始状态={
错误:“”,
成功:错
};
包装器=设置(初始状态);
});
测试(“无错误呈现组件”,()=>{
const component=findAttrByTest(包装器,“数据组件”);
expect(组件长度).toBe(1);
});
});
测试结果为


 FAIL  signUp.test.js (5.199s)
  render <SignUp>
    ✕ render component without error (45ms)

  ● render <SignUp> › render component without error

    expect(received).toBe(expected) // Object.is equality

    Expected: 1
    Received: 0

      43 |     test("render component without error", () => {
      44 |         const component = findAttrByTest(wrapper, 'data-component');
    > 45 |         expect(component.length).toBe(1);
         |                                  ^
      46 |     });
      47 | });
      48 | 

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        6.722s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.  console.log signUp.test.js:24
    <ContextConsumer>
      [function]
    </ContextConsumer>


signUp.test.js失败(5.199s)
提供
✕ 渲染组件时无错误(45毫秒)
● 渲染›无错误地渲染组件
expect(received).toBe(expected)//Object.is相等
预期:1
收到:0
43 |测试(“无错误渲染组件”,()=>{
44 | const component=findAttrByTest(包装器,“数据组件”);
>45 |预计(组件长度)。toBe(1);
|                                  ^
46 |     });
47 | });
48 | 
测试套件:1个失败,共1个
测试:1次失败,共1次
快照:共0个
时间:6.722s
运行与更改的文件相关的所有测试套件。
手表用法:按w键可显示更多信息。console.log signUp.test.js:24
[功能]

我通过使用.WrappedComponent解决了这个问题。这样,您就可以访问该组件了


import React from 'react';
import { configure, shallow, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';

import SignUp from './signUp';


configure({ adapter: new Adapter() });

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const push = jest.fn();
const historyMock = { push: jest.fn() };

const setup = (initialState = {}, props = {}) => {
    const store = mockStore(initialState);
    const wrapper = shallow(<SignUp.WrappedComponent history={historyMock} {...props} store={store} params={{
        router:
            push
    }} />);
    return wrapper;
}

const findAttrByTest = (wrapper, val) => {
    return wrapper.find(`[data-test="${val}"]`);
}

describe("render <SignUp>", () => {
    let wrapper;
    beforeEach(() => {
        const initialState = {
            error: '',
            success: false
        };
        wrapper = setup(initialState);
    });
    test("render component without error", () => {
        const component = findAttrByTest(wrapper, 'data-component');
        expect(component.length).toBe(1);
    });
});





从“React”导入React;
从“酶”导入{configure,shall,mount};
从'enzyme-Adapter-react-16'导入适配器;
从“redux模拟存储”导入configureMockStore;
从“redux thunk”导入thunk;
从“./SignUp”导入注册;
配置({adapter:newadapter()});
const middleware=[thunk];
const mockStore=configureMockStore(中间件);
const push=jest.fn();
const historyMock={push:jest.fn()};
const setup=(initialState={},props={})=>{
常量存储=模拟存储(初始状态);
常量包装器=浅();
返回包装器;
}
const findAttrByTest=(包装,val)=>{
返回wrapper.find(`[data test=“${val}”]`);
}
描述(“渲染”,()=>{
让包装纸;
在每个之前(()=>{
常量初始状态={
错误:“”,
成功:错
};
包装器=设置(初始状态);
});
测试(“无错误呈现组件”,()=>{
const component=findAttrByTest(包装器,“数据组件”);
expect(组件长度).toBe(1);
});
});

Hi Anjusha。您解决了这个问题吗?我已经通过使用
.WrappedComponent
解决了这个问题。通过这个您可以访问组件谢谢!这有帮助。但是,我不确定为什么使用
.WrappedComponent
会公开内部html。有人知道吗?