question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Test for value change in a Field

See original GitHub issue

Bug, Feature, or Question?

Question

First of all, I’d like to apologize for my bad english.

I’m trying to write a test where I can verify if a button is enabled or not, but I’m not managing to make it work.

The component that I have:

// TodoForm.js
import React from 'react';
import { withFormik, Form, Field } from 'formik';
import yup from 'yup';

const TodoForm = ({ isValid }) => (
  <Form>
    <Field name="todo" type="text" placeholder="Type your todo here..." />
    <button disabled={!isValid}>Add ToDo</button>
  </Form>
);

const EnhancedTodoForm = withFormik({
  mapPropsToValues: () => ({ todo: '' }),
  validationSchema: yup.object().shape({
    todo: yup.string().required(),
  }),
  handleSubmit: (values, { props }) => {},
})(TodoForm);

export default EnhancedTodoForm;

I want to change the ‘todo’ value (preferably via simulate) and see if the button gets enabled, but I’m not even able to change the value of Field.

Does anyone have any ideas? I’d love if it comes with an example ❤️.

Additional Information

This is the piece of code that I tried without success until now.

// TodoForm.test.js
import React from 'react';
import { shallow } from 'enzyme';

import TodoForm from './TodoForm';

describe('<TodoForm />', () => {
  let enhancedTodoForm;

  beforeEach(() => {
    enhancedTodoForm = shallow(<TodoForm />);
  });

  describe('interactions', () => {
    describe('user types something', () => {
      const newTodo = 'my new todo';

      it('`button` gets enabled', () => {
        const todoFormComponent = enhancedTodoForm.dive().dive();
        const field = todoFormComponent.find('Field');

        // this don't change the value, or at least i'm not figuring out how to access
        field.simulate('change', {
          persist: () => {},
          target: {
            name: 'todo',
            value: newTodo,
          },
        });
        // this also doesn't change the values prop inside the component
        enhancedTodoForm.dive().setProps({ values: { todo: newTodo } });

        expect(todoFormComponent.find('button').props().disabled).toBe(false);
      });
    });
  });
});

  • Formik Version: 0.11.11
  • React Version: 16.2.0
  • OS: Ubuntu 16.04
  • Node Version: 8.9.4
  • Package Manager and Version: yarn 1.3.2

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:8

github_iconTop GitHub Comments

52reactions
bmakuhcommented, Mar 7, 2018

Haha, after typing that out I realized my problem: I had a name attribute on the element, but I was assuming Enzyme was going to pass that element along as the event.target like in the real DOM, but that’s not true. Adding an explicit event.target.name in the simulated onChange fixed the problem.

18reactions
bmakuhcommented, Mar 21, 2018

@Ciaran0 yep, sure. The reason it wasn’t working for me was because I didn’t realize that I needed to explicitly provide a name property on the event object I was passing in, like this:

component.find('[data-test-id="email-field"]').simulate('change', {
  target: {
    name: 'email',
    value: 'aa@bb.cc'
  }
})

When your code runs in the browser, the native event will send the actual element as the target, in which case the name will be set already.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Testing Whether a Field's Value Is Changed
You can test whether a field's value has changed in the current transaction by using the built-in isAttributeChanged() function.
Read more >
How to check if any field value changes on the form?
I have requirement to check if any field values have been modified on the form and make "Suggestion" field mandatory if any of...
Read more >
check if the value of the input field changes - Stack Overflow
I can't change anything on that part. I can only create my own function to check when the field is populated or changed....
Read more >
How to validate field changes - The Hub, by Appfire
When a user edits an issue, validate the field value input · Go to Event-based Actions in the JMWE App administration. · Click...
Read more >
How to detect value change on hidden input field in JQuery
How to detect value change on hidden input field in JQuery ? ... In the <input> element with the type=”hidden”, the change() method...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found