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.

TypeError: formElement.checkValidity is not a function

See original GitHub issue

I have a simple test case for my form validation.

Each input element in a form has checkValidity method that checks whether the element has any constraints and whether it satisfies them.

I use it to go through some form elements and I check their validity. A simplified example could be:

    [
      form.querySelector('input[name="day"]'),
      form.querySelector('input[name="month"]'),
      form.querySelector('input[name="year"]'),
    ].every(formElement => formElement.checkValidity())

The code above would run perfectly in all modern browsers. That is sadly not true for Enzyme - when I run tests on a component containing the code above, I get TypeError.

TypeError: formElement.checkValidity is not a function

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
wojtekmajcommented, Jul 24, 2018

For the future wanderers: workaround in #374

0reactions
goonerifycommented, Aug 2, 2018

The Jest docs suggests mocking methods which are not implemented in JSDOM. I think this is a cleaner solution than polluting your environment because of tests.

In my specific case, I needed to validate a form and then inspect the classList of the form for the presence of a certain class, the presence of which would inform me about the form’s validity.

My solution was to mock the form’s properties e.g mock the native implementation of DOMTokenList for classList property inside

beforeAll(() => {
    window.DOMTokenList = jest.fn().mockImplementation(() => {
        return {
            list: [],
            remove: jest.fn().mockImplementation(function (item) {
                const idx = this.list.indexOf(item);

                if (idx > -1) {
                    this.list.splice(idx, 1)
                }
            }),
            add: jest.fn().mockImplementation(function (item) {
                this.list.push(item);
            }),
            contains: jest.fn().mockImplementation(function (item) {
                return this.list.indexOf(item) > -1;
            })
        };
    });
})

Then I used that to pass properties to the event handler. I’m able to access the form in my react component from the submit button with event.currentTarget.form

let mockClassList = new DOMTokenList();

submitBtn.simulate('click', {
        currentTarget: {
            form: {
                checkValidity: () => false,
                classList: mockClassList
            }
        },
        preventDefault: jest.fn(),
        stopPropagation: jest.fn()
    })

This allows me to set the validity of the form to false and true, and inspect the mockClassList for the presence of the was-validated class each time

    submitBtn.simulate('click', {
        currentTarget: {
            form: {
                checkValidity: () => false,
                classList: mockClassList
            }
        },
        preventDefault: jest.fn(),
        stopPropagation: jest.fn()
    });

    expect(mockClassList.contains('was-validated')).toBeTruthy();

    submitBtn.simulate('click', {
        currentTarget: {
            form: {
                checkValidity: () => true,
                classList: mockClassList
            }
        },
        preventDefault: jest.fn(),
        stopPropagation: jest.fn()
    });

    expect(mockClassList.contains('was-validated')).toBeFalsy();

FYI: I’m using Enzyme’s shallow rendering for this, mount doesn’t seem to work with this solution. However, I’m inclined to think that the other suggestion for mocking methods which are not implemented in JSDOM, when the method is executed directly in the tested file statement might just work with mount rendering

Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeError: checkValidity is not a function in JavaScript
The "checkValidity is not a function" error occurs when we try to call the checkValidity method on a value that is not an...
Read more >
html5 form checkValidity() method not found
Anyway I'd just add another way to do it using jQuery's .get([index]) function. It also retrieves the DOM element for the given index,...
Read more >
HTMLSelectElement.checkValidity() - Web APIs | MDN
The HTMLSelectElement.checkValidity() method checks whether the element has any constraints and whether it satisfies them.
Read more >
.checkValidity() is not a function : r/learnjavascript
checkValidity() is not a function. Hello I am learning the client side form validation,and I get the title error. One quick question if...
Read more >
Working with the HTML 5 Validation API
willValidate) { // this element is not disabled. ... The form element, too, has the checkValidity() and reportValidity() methods.
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