Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 139893

React Tests fails when i use document.getElementById (Jest+Enzyme)

$
0
0

I am working on a React form and have an onSubmit function to it. I only added below lines in onSubmit function.

const id = this.getErrorPositionById();
    const errorPosition = document.getElementById(id).offsetTop; //CANNOT READ PROPERTY 'offsetTop' of null
    window.scrollTo({
      top: errorPosition,
      behavior: "smooth"
    });

And this is the onSubmit function.

public onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const id = this.getErrorPositionById();
    const errorPosition = document.getElementById(id).offsetTop; 
    window.scrollTo({
      top: errorPosition,
      behavior: "smooth"
    });
    if (
      !this.state.isValid ||
      (!this.props.allowMultipleSubmits && this.state.isSubmitted)
    ) {
      return;
    }
    Promise.all(this.validateFields())
      .then((validationErrors: IValidationErrors[]) => {
        this.setError(Object.assign({}, ...validationErrors), () => {
          this.isFormValid() ? this.setSubmitted(e) : this.scrollFormToView();
        });
      })
      .then(() => {
        const newErrors = this.state.errors;
        this.setState({ errors: { ...newErrors, ...this.props.apiErrors } });
      });
  };

Here is the test case

  beforeEach(() => {
    jest.clearAllMocks();
    formFields = jest.fn();
    onSubmit = jest.fn();
    onValidate = jest.fn();
    validate = jest.fn();
    mockPreventDefault = jest.fn();
    mockEvent = jest.fn(() => ({ preventDefault: mockPreventDefault }));
    mockValidateAllFields = jest.fn(() => Promise);
    mockChildFieldComponent = { validate };
    instance = formWrapper.instance();
  });


it("should not reValidate if form has been submitted already", () => {
    instance.validateFields = mockValidateAllFields;
    instance.setSubmitted();
    expect(instance.state.isSubmitted).toBe(true);
    instance.onSubmit(mockEvent());
    expect(mockValidateAllFields).toHaveBeenCalledTimes(0);
  });

The test case fails with error ' TypeError: Cannot read property 'offsetTop' of null' on below line

const errorPosition = document.getElementById(id).offsetTop; 

Can someone please help me understand how to eliminate this error.


Viewing all articles
Browse latest Browse all 139893

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>