【发布时间】:2021-06-02 22:17:05
【问题描述】:
所以我正在尝试测试是否应该为已登录的用户显示注销链接。
在测试中传递的值确定用户是登录还是退出。
isAuthenticated 是一个布尔值:
true = 用户已登录,
false = 用户已注销
我的猜测是问题出在测试中传递了 isAuthenticated 参数(一切正常,而手动测试问题在测试中是 100%)
describe('authenticated users', () => {
test('should contain authLinks', () => {
const logoutAction = jest.fn();
render(
<Provider store={store}>
<Router>
<Navbar isAuthenticated={true} logoutAction={logoutAction} />
</Router>
</Provider>
);
const authLinks = screen.getByTestId('authLinks');
});
});
错误:
TestingLibraryElementError: Unable to find an element by: [data-testid="authLinks"]
组件:
import React, { Fragment } from 'react';
import { Link, NavLink } from 'react-router-dom';
import { connect } from 'react-redux';
import { logoutAction } from '../actions/auth';
const navbar = ({ isAuthenticated, logoutAction }) => {
const authLinks = (
<li data-testid='authLinks'>
<button onClick={logoutAction}>Logout</button>
</li>
);
const guestLinks = (
<div data-testid='guestLinks'>
<li>
<NavLink exact to='/login'>
Login
</NavLink>
</li>
<li>
<NavLink exact to='/signup'>
Sign Up
</NavLink>
</li>
</div>
);
return (
<nav>
<Link to='/'>Auth System</Link>
<div>
<ul>
<li>
<NavLink exact to='/'>
Home
</NavLink>
</li>
<>{isAuthenticated ? authLinks : guestLinks}</>
</ul>
</div>
</nav>
);
};
const mapStateToProps = (state) => ({
isAuthenticated: state.authReducer.isAuthenticated,
});
export default connect(mapStateToProps, { logoutAction })(navbar);
【问题讨论】:
-
isAuthenticated来自mapStateToProps,它需要在商店中,而不是作为道具在您的测试中传递。
标签: reactjs jestjs integration-testing react-testing-library