0

I make a very easy component to test the TestUtils.Simulate reactJS method. But I don't know why this method doesn't update the value of my component. I guess I wrote my code on the wrong way.

This is my little component :

    'use strict';

var React = require('react');

var MyComponent = React.createClass({


    getInitialState: function () {
        return {value: 'a'};
    },
    handleChange: function (event) {
        this.setState({value: event.target.value});
    },
    render: function () {
        return (
            <div>
                <input
                    ref="inp"
                    type="text"
                    value={this.state.value}
                    onChange={this.handleChange}
                />
            </div>
        );
    }
});

module.exports = MyComponent;

And this is the test page :

    jest.disableAutomock();
jest.unmock('../resources/assets/js/testcomponents/testvalue');


var React = require('react'),
    MyComponent = require('../resources/assets/js/testcomponents/testvalue.js'),
    TestUtils = require('react-addons-test-utils'),
    ReactDOM = require('react-dom');



describe('MyComponent', function () {

    var AppElement = TestUtils.renderIntoDocument(<MyComponent/>);
    var DomElement = ReactDOM.findDOMNode(AppElement);

    var input = DomElement.getElementsByTagName('input')[0];



    console.log('INPUT 1 as string: ' + input.outerHTML);

    it('type', function () {
        console.log('type=' + input.getAttribute('type'));
        expect(input.getAttribute('type')).toEqual('text');
    });

    it('value', function () {
        console.log('value=' + input.getAttribute('value'));
        expect(input.getAttribute('value')).toEqual('a');
    });

    it('change', function (){


        TestUtils.Simulate.change(input, {target: {value: 'giraffe'}});
        expect(input.getAttribute('value')).toEqual('giraffe');
    });
});

The line TestUtils.Simulate.change(input, {target: {value: 'giraffe'}}); doesn't make anything

1 Answer 1

1

I think the main issue is that you compare against

input.getAttribute('value')

which only contains the original value. You have to check the updated value like:

expect(input.value).toEqual('giraffe');

I set up a working jasmine test on jsfiddle Click

Sign up to request clarification or add additional context in comments.

1 Comment

This is the opposite of my experience. I had input.value, but the value wasn't updating. I changed it to input.getAttribute('value'), and it's updating.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.