简体   繁体   中英

React Unit Testing: TypeError: Cannot read property 'test' of undefined

I am unit-testing a React App using karma-jasmine. However, there is recurrent error as follows

TypeError: Cannot read property 'test' of undefined

  at ValidatedInput.validateInput (src/components/ValidatedInput.js:47:42)
  at ValidatedInput.isValid (src/components/ValidatedInput.js:33:27)
  at Object.<anonymous> (src/__tests__/validated_input-test.js:64:24)
  at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
  at process._tickCallback (internal/process/next_tick.js:109:7)

Following is my test file

validated_input-test.js

    describe('functions', () => {
        const componentToCheckFunctions = TestUtils.renderIntoDocument(
            <ValidatedInput
                type={'password'}
                name={'password'}
                title={'Password'}
                value={'Sample123Test'}
                placeholder={'Sample Placeholder'}
                onChange={() => {}}
                onComponentMounted={() => {}}
                validaions={/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/}
                validationError={'Invalid Password Format'}
        />);

        const renderedDOMNode = TestUtils.findRenderedDOMComponentWithClass(
            componentToCheckFunctions, 'form-input'
        );

        it('should check validate password', () => {
            expect(shallow(<ValidatedInput />
            ).instance().isValid(renderedDOMNode)).equals(true);
        });

    });

and the file for testing

ValidatedInput.js

import React, { Component } from 'react';

class ValidatedInput extends Component {
    constructor(props) {
        super(props);

        this.state ={
            validations: this.props.validations,
            validationError: this.props.validationError
        };

        this.handleChangeValue = this.handleChangeValue.bind(this);
        this.isValid = this.isValid.bind(this);
        this.validateInput = this.validateInput.bind(this);
    }

    handleChangeValue(e) {
        this.props.onChange(e.target.value);
        var isValidField = this.isValid(e.target);
    }

    isValid(inputElement) {
        if (inputElement.getAttribute('required') !== null && inputElement.value === "") {
            inputElement.classList.add('Error');
            inputElement.nextSibling.textContent = this.props.validationError;
            return false;
        } else {
            inputElement.classList.remove('Error');
            inputElement.nextSibling.textContent =  '';
        }

        if(inputElement.value !== "") {
            if(!this.validateInput(inputElement.value)) {
                inputElement.classList.add('Error');
                inputElement.nextSibling.textContent = this.props.validationError;
                return false;
            } else {
                inputElement.classList.remove('Error');
                inputElement.nextSibling.textContent =  '';
            }
        }
            return true;
    }

    validateInput(value) {
        var regularExpressionToBeMatched = this.props.validations;
        return this.state.validations.test(value);
    }

    componentDidMount() {
        if (this.props.onComponentMounted) {
            this.props.onComponentMounted(this);
        }
    }

    render () {
        return (
            <div className="form-group">
                <div className="col-5 text-center">
                    <label htmlFor={this.props.name}>{this.props.title}</label>
                </div>
                <div className="col-5 text-center">
                    <input
                        className="form-input text-center"
                        type={this.props.type}
                        ref={this.props.name}
                        name={this.props.name}
                        value={this.props.value}
                        required={this.props.isRequired}
                        placeholder={this.props.placeholder}
                        onChange={this.handleChangeValue}
                    />
                    <span className='Error'></span>
                </div>
            </div>
        );
    }
}

export default ValidatedInput;

Logging this.props.validations produces undefined . I tried passing props in shallow<ValidatedInput /> but the error still persists. Any suggestions on how to deal with error or structure of code? Thanks.

validaions={/^(?=. [A-Za-z])(?=. \\d)[A-Za-z\\d]{8,16}$/}

*validations

typo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM