gpt4 book ai didi

reactjs - 用 enzyme 浅渲染找不到元素

转载 作者:行者123 更新时间:2023-12-03 13:35:57 25 4
gpt4 key购买 nike

我正在尝试对我的 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);

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

当此测试运行时,它失败并提示“expected 0 to be 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com