0

我配置了一个容器以使用 redux-mock-store 测试到最后一个版本,但我遇到了一些问题。find() 函数不起作用。我曾经收到零节点和零长度。当我使用 mount 代替浅层函数时,这是可行的,但是我遇到了无法识别 redux mapDispatchToProps 的问题。我如何保证会调用该操作?我不想测试商店而是测试动作功能,因为我使用 thunk。我的推理对吗?

我的容器:

import React, { useState } from 'react'
import { connect } from 'react-redux'
import { Redirect } from 'react-router-dom'

import styles from './Auth.module.css'

import Input from '../../components/UI/Input/Input'
import Button from '../../components/UI/Button/Button'
import Logo from '../../components/UI/Logo/Logo'
import Spinner from '../../components/UI/Spinner/Spinner'
import { auth as authAction } from '../../store/actions/index'
import { checkValidity } from '../../shared/utility'

export const Auth = (props) => {

    const [formIsValid, setFormIsValid] = useState(false)
    const [authForm, setAuthForm] = useState({
        email: {
            elementType: 'input',
            elementConfig: {
                type: 'email',
                placeholder: 'Enter your email'
            },
            value: '',
            validation: {
                required: true,
                isEmail: true
            },
            valid: false,
            touched: false
        },
        password: {
            elementType: 'input',
            elementConfig: {
                type: 'password',
                placeholder: 'Enter your password'
            },
            value: '',
            validation: {
                required: true,
                minLength: 6
            },
            valid: false,
            touched: false
        },
    })

    const inputChangeHandler = (event, controlName) => {
        const updatedControls = {
            ...authForm,
            [controlName]: {
                ...authForm[controlName],
                value: event.target.value,
                valid: checkValidity(event.target.value, authForm[controlName].validation),
                touched: true
            }
        }

        let formIsValid = true;
        for (let inputIdentifier in updatedControls) {
            formIsValid = updatedControls[inputIdentifier].valid && formIsValid
        }

        setAuthForm(updatedControls)
        setFormIsValid(formIsValid)
    }

    const submitHandler = (event, signup) => {
        event.preventDefault()
        props.onAuth(
            authForm.email.value,
            authForm.password.value,
            signup
        )
    }

    const formElementsArray = []
    for (let key in authForm) {
        formElementsArray.push({
            id: key,
            config: authForm[key]
        })
    }

    let formFields = formElementsArray.map(formElement => (
        <Input
            key={formElement.id}
            elementType={formElement.config.elementType}
            elementConfig={formElement.config.elementConfig}
            value={formElement.config.value}
            invalid={!formElement.config.valid}
            shouldValidate={formElement.config.validation}
            touched={formElement.config.touched}
            changed={(event) => inputChangeHandler(event, formElement.id)} />
    ))

    let form = (
        <>
            <form onSubmit={(event) => submitHandler(event, false)}>
                {formFields}
                <Button
                    disabled={!formIsValid}
                    btnType="Default">Log In</Button>
            </form>
            <Button
                clicked={(event) => submitHandler(event, true)}
                disabled={!formIsValid}
                btnType="Link">Sign Up</Button>
        </>
    )
    if (props.loading) {
        form = <Spinner />
    }

    const errorMessage = props.error ? (
        <div>
            <p style={{ color: "red" }}>{props.error}</p>
        </div>
    ) : null;

    let authRedirect = null;
    if (props.isAuthenticated) {
        authRedirect = <Redirect to={'/'} />
    }

    return (
        <main className={styles.Auth}>
            {authRedirect}
            <div className={styles.AuthForm}>
                <h1>Log in to your account</h1>
                <Logo height="3em" />
                {errorMessage}
                {form}
            </div>
        </main>
    )
}

const mapStateToProps = (state) => {
    return {
        loading: state.auth.loading,
        error: state.auth.error,
        isAuthenticated: state.auth.token !== null,
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        onAuth: (email, password, isSignup) => dispatch(authAction(email, password, isSignup))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Auth)

我的测试:

import React from 'react';
import { Redirect } from 'react-router-dom';
import thunk from 'redux-thunk';

import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import configureStore from 'redux-mock-store';

import Auth from './Auth';
import Spinner from '../../components/UI/Spinner/Spinner';
import Button from '../../components/UI/Button/Button';
import Input from '../../components/UI/Input/Input';

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

const setup = () => {
    const props = {
        onAuth: jest.fn()
    }

    const middlewares = [thunk]
    const mockStore = configureStore(middlewares);
    const initialState = {
        auth: {
            token: null,
            email: null,
            error: null,
            loading: false
        }
    };
    const store = mockStore(initialState);

    const enzymeWrapper = shallow(<Auth store={store} {...props} />).dive();

    return {
        enzymeWrapper,
        props,
        store
    }
}

describe('<Auth />', () => {

    it('should calls onSubmit prop function when form is submitted', () => {
        const { enzymeWrapper: wrapper, props: reduxProps, store } = setup();
        const form = wrapper.find('form');

        form.simulate('submit', {
            preventDefault: () => { }
        });
        expect(wrapper.props().onAuth).toHaveBeenCalled();
    });
});
4

1 回答 1

1

为了能够在Auth没有存储连接的情况下测试类,您需要使用命名导入而不是默认导入。PFB 要在测试文件中添加用于导入 Auth 组件的行:

import { Auth } from './Auth'; // notice the curly braces around the component name

此外,使用这种方法,您无需在渲染时将 store 作为 props 传递给组件,并且可以将操作作为模拟函数传递(您已经在为操作执行此onAuth操作)。您也可以通过这种方法使用浅层。

于 2019-05-20T18:03:21.977 回答