用酶进行浅层渲染无法找到元素

时间:2018-04-15 18:51:19

标签: reactjs unit-testing jestjs enzyme

我正在尝试对我的一个React组件进行单元测试,但是Enzyme的浅层渲染方法是说它无法在组件中找到元素。该组件根据身份验证支持呈现不同的导航链接。

导航组件:

    class Header extends Component {

      renderLoginNav() {
        switch(this.props.auth) {
            case null:
                return;
            case false:
                return (
                    <li key={ 1 }><a className="nav-link" href="/auth/google" 
                     id="google">Login</a></li>
                );
            default: 
                return [
                    <li key={ 2 } className="nav-item">
                        <a className="nav-link" href="/lists">Dashboard</a></li>,
                    <li key={ 3 } className="nav-item">
                        <a className="nav-link" href="/credits">Credits</a></li>,
                    <li key={ 4 } className="nav-item">
                        <a className="nav-link" href="/api/logout">Logout</a></li>
                ];
        }
    }
    render() {
        return (
                <nav>
                    <ul>
                        {this.renderLoginNav()}
                    </ul>
                </nav>
        );
    }
}
function mapStateToProps(state) {
    return {
        auth: state.auth
    }
}
export default connect(mapStateToProps)(Header);

酶测试:

import React from 'react';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import configureStore from 'redux-mock-store';
import Header from './';

configure({ adapter: new Adapter() });
const middlewares = [];
const mockStore = configureStore(middlewares);
it('displays correct nav when authenticated', () => {
        const initialState = { auth: {} };
        const store = mockStore(initialState);
        const wrapper = shallow(<Header store={store} />);

        expect(wrapper.find('.nav-link').length).toBe(3);
    })

当此测试运行时,它无法说&#34;预期0为3&#34;。我误解了浅层渲染方法的工作原理吗?或者我的测试设置有缺陷吗?

2 个答案:

答案 0 :(得分:2)

导航组件:

// export the component without connecting it
export class Header extends React.Component {
  ...
}

export default connect(mapStateToProps)(Header)

测试:

import { Header} from '../Header' // pull off unconnected component

it('displays correct nav when authenticated', () => {
  // see how we mock the props received by the store
  let wrapper = shallow(
    <Header
      auth={{}}
    />
  )
  expect(wrapper.find('.nav-item')).toHaveLength(3) // jest syntax
})

答案 1 :(得分:1)

对于Redux连接的组件,在使用.dive()时必须使用shallow

const wrapper = shallow(<Header store={store} />).dive();

请阅读这篇文章:Testing a Redux-connected component using Enzyme issueShallowWrapper .dive()