28

How do you set the text of a text input and then test it's value with React / Enzyme?

const input = wrapper.find('#my-input');

input.simulate('change',
  { target: { value: 'abc' } }
);

const val = input.node.value;

//val is ''

All the solutions here appear not to work..

2

6 Answers 6

33

To really understand what's happening in your code it would be useful to see your component code (specifically your onChange handler.

However, in regards to the following code:

input.simulate('change', {target: {value: 'abc'}});

This won't actually change the value of your <input /> element, instead it just causes your onChange function to be run and be provided an event object that looks like {target: {value: 'abc'}}.

The idea is that your onChange function would update your state or store, so triggering this function should result in your DOM being updated. If you don't actually have an onChange handler defined using input.simulate('change') won't do anything.

So, if your goal is to actually set the value of an input and not trigger an onChange handler then you can use JS to manually update the DOM using something like wrapper.find('#my-input').node.value = 'abc'; however this is circumventing React's render cycle and you'll likely see this value cleared/removed if you do anything to trigger a re-render.

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

4 Comments

I am trying to set the value with input.node.value = "Test", and I am getting this error TypeError: Can't add property value, object is not extensible. Any ideas?
@jhamm Check out my answer below.
you might need to remove target / value: input.simulate('changeText', '6');
I also had the issue of: TypeError: Cannot add property value, object is not extensible. What resolved it for me was changing node.find('#id_name').get(0).value = to node.find('#id_name').instance().value =
25

I'm using React 16 and Enzyme 3.10 over here and this completely worked for me (after trying too many different suggestions out there):

wrapper.find("input").instance().value = "abc";

Apparently, in previous versions you could use node or getNode() instead of instance(), which were parts of my many previous attempts.

4 Comments

I used .node but Enzyme told me to use getElement() but that gave me the react element and not the dom element. Thx for sharing the instance() function.
typescript is failing with error: TS2339: Property value does not exist on type Component<{}, {}> . Can you please help?
@user2133404 Sorry, man...but I have no idea how to tackle this, given I've never worked with Typescript before.
Typescript needs to know what type of element you're dealing with specifically. In this case wrapper.find("input").instance<HTMLInputElement>().value = "abc"; would work.
11

This works for both Enzyme 3 and Enzyme 2:

wrapper.find('input').getDOMNode().value = 'new value';
wrapper.find('input').simulate('change');

.getDOMNode() can be used like .node in Enzyme 2 and like .instance() in Enzyme 3.

1 Comment

Enzyme 3.3.x wrapper.getDOMNode is not a function. Looks like it's only for mount github.com/airbnb/enzyme/blob/master/docs/api/ReactWrapper/…
2

If using TypeScript you can do the following

wrapper.find('input').getDOMNode<HTMLInputElement>().value = 'new value';
wrapper.find('input').simulate('change');

Comments

0

Here it works for me..

I have change the input text, with value updation. And Update my DOM property.

.update()

After updating I am checking the button disable property with input mobile number length use cases.

const input = MobileNumberComponent.find('input')
input.props().onChange({target: {
   id: 'mobile-no',
   value: '1234567900'
}});
MobileNumberComponent.update()
const Footer = (loginComponent.find('Footer'))
expect(Footer.find('Buttons').props().disabled).equals(false)

Comments

0

I found that I had to use Jest's fake time to give my React onChange function time to run and note the new value of the text input. Here's the full test (though, no setup), using React, jest, and enzyme:

describe('Modal with text input', () => {
  beforeEach(() => {
    jest.useFakeTimers();
  });

  afterEach(() => {
    jest.clearAllTimers();
    jest.useRealTimers();
  });

  it('enter email, get email tag', () => {
    const modal = render();
    let textField = modal.find('input[data-test-id="assignEmailInput"]');
    let tags = modal.find('[className*="spectrum-Tag--removable"]');

    // initial load
    expect(textField.prop('value')).toBe('');
    expect(tags).toHaveLength(3);

    // "write" in the input
    textField.simulate('click');
    textField.simulate('change', { target: { value: '[email protected]' } });

    // enact the writing for jest
    jest.advanceTimersByTime(150);
    modal.update();
    textField = modal.find('input[data-test-id="assignEmailInput"]');
    tags = modal.find('[className*="spectrum-Tag--removable"]');

    expect(textField.prop('value')).toBe('[email protected]');
    expect(tags).toHaveLength(3);
    const expected = ['[email protected]', '[email protected]', '[email protected]'];
    tags.forEach((tag, i) => expect(tag.contains(expected[i])).toBe(true));

    // enact the onBlur function that sets tags
    textField.simulate('blur');
    modal.update();
    textField = modal.find('input[data-test-id="assignEmailInput"]');
    tags = modal.find('[className*="spectrum-Tag--removable"]');

    expect(textField.prop('value')).toBe('');
    expect(tags).toHaveLength(4);
    expected.push('[email protected]');
    tags.forEach((tag, i) => expect(tag.contains(expected[i])).toBe(true));
  });
});

Comments

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.