测试 React Redux - 无法读取未定义的属性或未定义的包装器

2024-04-21

我在为我的测试套件在组件中设置 Redux 存储时遇到了一些问题。问题是,即使我尝试未连接的挂载,测试也会在 authState 中查找变量时抛出错误。我有以下组件:

import React, { Component } from 'react';
import { Link, Redirect } from "react-router-dom";
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as authActions from '../../../actions/auth.actions';

export class PasswordReset extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            emailConfirm: '',
            message: ""
        };
    }

    handleChange = e => {
        e.preventDefault();
        const { value, name } = e.target;

        if (name === 'email') {
            this.setState({...this.state, email: value.trim()});
        } else if (name === 'secondary') {
            this.setState({...this.state, emailConfirm: value.trim()});
        }
    }

    handleSubmit = e => {
        e.preventDefault();
        if (this.state.email.length === 0 && this.state.emailConfirm.length === 0) {
            this.setState({message: "Please Enter and Confirm Email Before Submit"});
            return;
        }

        if (this.state.email !== this.state.emailConfirm) {
            this.setState({message: 'Emails Do Not Match, Please Try Again'});
            return;
        }

        this.props.authActions.resetPassword(this.state.email);
    }

    render() {
        if (this.props.authState.resetStatus === 'reset') {
            return <Redirect to='/login' />
        }
        const error = this.props.authState.resetError === 'TypeError: Failed to fetch' ? 'Agent Id does not exist' : false
        return (
            <div className={'container-login100'}>
                <div className={'wrap-login100 p-t-85 p-b-20'}>
                    <form className={'login100-form validate-form'}>
                        <span className={'login100-form-title p-b-70'}>Reset Password</span>
                        <div className={'wrap-input100 validate-input m-t-85 m-b-35'}>
                        <div style={{margin: '0 auto', alignItems: 'center', justifyContent: 'center', display: 'flex', color: 'red'}}>
                        {error || this.state.message}
                        </div>
                            <input
                                onChange={e => this.handleChange(e)}
                                className={'input100'}
                                name='email'
                                value={this.state.email}
                                placeholder="Please Enter Your Email"
                                required
                            />
                        </div>
                        <div className={'wrap-input100 validate-input m-t-85 m-b-35'}>
                            <input
                                onChange={e => this.handleChange(e)}
                                className={'input100'}
                                name="secondary"
                                value={this.state.secondary}
                                placeholder="Please Confirm By Re-entering Your Email"
                                required
                            />
                        </div>
                        <div className={'container-login100-form-btn'}>
                            <button className={'login100-form-btn btn-disabled'} onClick={e => this.handleSubmit(e)}>Reset Password</button>
                        </div>
                        <div className={'container-login100-form-btn'}>
                            <Link to='/login'>Back to Login</Link>
                        </div>
                    </form>
                </div>
            </div>
        )
    }
}

const mapStateToProps = state => ({
    authState: state.auth,
})

const mapDispatchToProps = dispatch => ({
    authActions: bindActionCreators({resetPassword: authActions.resetPassword}, dispatch),
})

export default connect(mapStateToProps, mapDispatchToProps)(PasswordReset);

以及以下测试结构:

import React from 'react';
import configureStore from 'redux-mock-store';
import Enzyme, {mount, shallow} from 'enzyme';
import Provider from 'react-redux';
import Adapter from 'enzyme-adapter-react-16';

import ConnectedPasswordReset, {PasswordReset} from '../';

Enzyme.configure({adapter: new Adapter()});

const mockStore = configureStore();
let wrapper, store, mWrapper;
const initialState = {isLoggedIn: false, isInProgress: false, email: null, error: null, resetError: null, resetStatus: null};

describe('PasswordReset component', () => {
    beforeEach(() => {
        store = mockStore(initialState);
        wrapper = shallow(<PasswordReset store={store} />);
        mWrapper = mount(<Provider store={store}><ConnectedPasswordReset /></Provider>);
    })

    it('shallow - should have initial state.email of ""', () => {
        expect(wrapper.state().email).toEqual('');
    });

    it('mount - should have a initial state.email of ""', () => {
        expect(mWrapper.state().email).toEqual('');
    });
});

我得到以下输出:


这是最终对我有用的设置。您也可以使用 mount,但您需要导入 Router 并将组件包装在其中。

import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { PasswordReset } from '../';

Enzyme.configure({adapter: new Adapter()});

const setup = () => {
    let props = {
        authState: {
           isLoggedIn: false, 
           isInProgress: false, 
           email: null, 
           error: null, 
           resetError: null, 
           resetStatus: null
        },
        authActions: {
            login: jest.fn(),
            resetPassword: jest.fn()
        }
    }

    let resetWrapper = shallow(<PasswordReset {...props}/>);

    return {props, resetWrapper};
};

describe('PasswordReset component', () => {
    const {resetWrapper} = setup();

    describe('initial render', () => {
        it('should have initial state.email of ""', () => {
            expect(resetWrapper.state('email')).toEqual('');
        });

        it('should have a initial internal state.emailConfirm of ""', () => {
            expect(resetWrapper.state('emailConfirm')).toEqual('');
        });

        it('should have one form component', () => {
            expect(resetWrapper.find('form').length).toBe(1);
        })

        it('should have two input fields', () => {
            expect(resetWrapper.find('input').length).toBe(2);
        });
    });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

测试 React Redux - 无法读取未定义的属性或未定义的包装器 的相关文章

  • React Native:如何在组件中添加脚本标签

    我正在尝试在 React Native 应用程序的组件内添加标签 下面是我的代码 它似乎不起作用 谁能告诉我如何解决这个问题 import React Component from react import PropTypes from p
  • 重构 withState 如何更新 props 更改

    我有一个更高阶的组件 我尝试对其进行一些修改 我不熟悉重组 这就是我的组件
  • React i18next Backend-Path 在本地和生产环境中不同

    我正在使用一个反应应用程序react i18next并加载翻译i18next xhr backend i18n use Backend use initReactI18next passes i18n down to react i18ne
  • Webpack 加载器与插件;有什么不同?

    webpack 中的加载器和插件有什么区别 The 插件文档 https webpack github io docs using plugins html只是说 使用插件添加通常与 webpack 中的捆绑包相关的功能 我知道 babel
  • 将 React 与 ejs 结合使用?

    我有一个使用 React 状态构建的前端 旨在根据用户操作进行调整 然而 我的前端 React 也旨在显示并允许操作我的服务器端数据 目前我的视图引擎是EJS 我用它来显示数据 举一个广泛的例子 return div class col m
  • 如何过滤javascript对象数组

    我有两个数组 我正在使用 PubSidebar 过滤基于 groupKey 的内容 let groupKey oaDeal Journals Deposit This array of object will be filtering wi
  • 类型错误:无法读取未定义的属性“存在”

    我正在尝试为 jsx 文件编写一个测试用例 在此我能够传递 proptypes 但不是我正确传递 proptypes 的地方 当我运行测试用例时出现错误 下面提供我的错误 测试用例和代码 类型错误 无法读取未定义的属性 存在 不知道如何让它
  • 如何在 React JS 组件中预加载图像?

    我目前正在渲染一个子组件signInError发生 这signInError存储在父组件中 如果不为 null 则渲染
  • 如何删除默认的故事书画布样式?

    Storybook 将默认样式应用于故事画布 iframe 这使得我的故事无法呈现应有的样子 如何摆脱 Storybook 的默认样式 例如 这是默认样式h2元素 通过 Storybook 的 page css 那个的来源page css
  • React Native + Jest EMFILE:打开文件太多错误

    我正在尝试运行 Jest 测试 但收到以下错误 读取文件时出错 Users mike dev react TestTest node modules react native node modules yeoman environment
  • 如何在 NextJS 应用程序中处理公共和私有路由?

    我正在开发一个具有公共和管理路由的应用程序 在过去的 CRA 应用程序中 我们使用了自定义路由元素 但我们在 nextjs 中没有 Thins 我们有很多公共页面 我们有 20 个私人页面 路线 在 nextjs 中处理受保护的经过身份验证
  • 带有 React 的 Google Analytics 无法正常工作

    我在我的反应项目中使用谷歌分析 即使我在线 它也不会显示任何活跃用户 我尝试过在网上找到的不同方法 但似乎都不起作用 我只在本地主机上尝试过 而不是在已部署的网站上尝试过 但我认为它应该仍然有效 这是我的代码 我的应用程序 js impor
  • 博览会错误:连接 ETIMEDOUT 104.197.216.164:443

    我尝试在我的 android 上通过 expo 运行 React Native android 模拟器 我在过去 24 小时内一直遇到此错误 Error connect ETIMEDOUT 104 197 216 164 443 at TC
  • 生产中的 Webpack:为什么 React Native 会出现错误?

    我有一个测试应用程序 安装了以下内容 dependencies express 4 14 0 react 15 3 2 react dom 15 3 2 devDependencies babel 6 5 2 babel core 6 18
  • 是否可以用 json 进行表达式/计算?

    我使用出色的 json server 作为应用程序的后端 它对于访问自定义端点以检索一些数据非常有用 但是如果它允许我进行计算 表达式以便我也可以模仿后端行为 那将会非常有用 以这个数据结构为例 products name football
  • Phonegap 图像未显示

    我无法让图像在我的phonegap 版本中正常工作 我读过绝对路径可能不起作用 所以我尝试了绝对路径和相对路径 但仍然没有运气 我包括这样的图像
  • 有没有办法从函数内单击导航链接?

    基本上 我正在延迟导航 单击链接后 onClick 处理程序通过检查条件并调用另一个函数来阻止导航 如果满足特定条件 则仅该页面导航到另一个页面 那么我如何从该函数中触发 Navlink 单击 我能够通过使用解决这个问题event prev
  • 如何模拟一个方面

    我目前正在使用aspectj 开发一些监控工具 因为这个工具应该是技术独立的 尽可能 所以我没有使用 Spring 进行注入 但我希望我的方面能够经过单元测试 方面示例 Aspect public class ClassLoadAspect
  • 如何使用材料用户界面和样式组件定位按钮基础

    使用ToggleButton and ToggleButtonGroup组件来自material ui从材料 ui 开始盖茨比模板 https github com mui org material ui tree master examp
  • 使用 ES6 静态函数时,我得到“没有这样的方法”

    我正在尝试为我在 React Native 中工作的项目创建一个包含静态函数的 utils 类 我读到了如何在 StackOverFlow 中创建静态函数question https stackoverflow com questions

随机推荐