【问题标题】:how to test component while passing boolean value with react testing library and jest如何在使用反应测试库和笑话传递布尔值的同时测试组件
【发布时间】: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


【解决方案1】:

如前所述:“isAuthenticated 来自 mapStateToProps,它需要在商店中,而不是在您的测试中作为道具传递”

使用 jonrsharpe 的建议我想通了:这是我的工作测试

describe('authenticated users', () => {
    test('should contain authLinks', () => {
        store.dispatch({ type: 'LOGIN_SUCCESS', payload: { isAuthenticated: true } });
        render(
            <Provider store={store}>
                <Router>
                    <Navbar />
                </Router>
            </Provider>
        );
        const authLinks = screen.getByTestId('authLinks');
    });
});

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 1970-01-01
    • 2021-07-11
    • 2021-09-27
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2018-08-24
    • 2021-02-04
    相关资源
    最近更新 更多