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

导航组件:

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

enzyme 测试:
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);
    })

运行此测试时,它不会说“预期的0等于3”。我是否误解了浅渲染方法的工作原理?还是我的测试设置存在缺陷?

最佳答案

导航组件:

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

关于reactjs - 用 enzyme 进行浅渲染找不到元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49845614/

10-11 00:04