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

时间:2019-05-16 12:06:09

标签: reactjs unit-testing jestjs enzyme

我在React js中使用笑话和酶进行单元测试。 当我使用“ 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)));


这是测试文件

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);
    });
});

测试结果是


 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>

1 个答案:

答案 0 :(得分:0)

我已经通过使用.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);
    });
});