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.

Use a Real MutationObserver Shim when Testing

See original GitHub issue

When attempting to use this library with @testing-library/react I was having issues where calling a useState update in my submit callback was not being seen by the test runner. I used the information in https://github.com/react-hook-form/react-hook-form/issues/260 to get started. I could still log the updates in the component so it didn’t seem to be a component problem.

I ended up adding https://github.com/megawac/MutationObserver.js/tree/master and this solved my problem. Assuming you agree with my analysis, the samples should be updated to reflect this. It took me quite some time to track the issue down.

Relevant repro code below

// Form.jsx

import * as React from 'react';

import {useState} from 'react';

import useForm from 'react-hook-form';

const Form = () => {
  const { register, handleSubmit, errors } = useForm(); // initialise the hook
  
  const [val, setVal] = useState(false);

  const onSubmit = (data) => {

    setVal(true);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input data-testid="myinput" name="myinput" ref={register} /> {/* register an input */}
      
      <button type="submit" data-testid="login-submit"> Login </button>

      {val && <div data-testid="my-res"> Value Set! </div>}
    </form>
  );
};

export default Form;


// Form.test.jsx

import React from 'react';

import { render, cleanup, fireEvent } from '@testing-library/react';

import Form from './Form';

afterEach(cleanup);

beforeEach(() => {

  // This does not work
  global.MutationObserver = class {
    constructor() {}
    disconnect() {}
    observe() {}
  };

  // // This will!
  // require('mutationobserver-shim');
});

describe('React-Hook-Form + setSTate', () => {

  it('Displays the updated value', async () => {

    const { getByTestId, findByTestId } = render(<Form />);

    const myinput = getByTestId(/myinput/i);

    const submitButon = await findByTestId('login-submit');

    fireEvent.change(myinput, { target: { value: 'set random input' } });

    fireEvent.click(submitButon);

    await findByTestId('my-res')
  });

});

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:15 (9 by maintainers)

github_iconTop GitHub Comments

1reaction
thainararogeriocommented, Aug 24, 2020

For those who came into this post nowadays, there is no need to use cleanup anymore if you are using mocha, Jest or Jasmine: https://testing-library.com/docs/react-testing-library/api#cleanup

Read more comments on GitHub >

github_iconTop Results From Across the Web

Testing MutationObserver with Jest - Stack Overflow
You can use Jest mock functions to mock MutationObserver . This allows you to test instances of it in your code. See my...
Read more >
mutationobserver-shim examples - CodeSandbox
Learn how to use mutationobserver-shim by viewing and forking example apps that make use of mutationobserver-shim on CodeSandbox.
Read more >
Testing Stimulus - Hrvoje Šimić (Shime)
We're going to use Jest for testing; Babel packages to make it play nice with Jest and mutationobserver-shim for shimming MutationObserver API ...
Read more >
React testing library and react-hook-form components - Reddit
Hi there, we are using MutationObserver for detecting input get unmounted from the tree, to ensure that unwanted inputs don't get into the ......
Read more >
MutationObserver - Web APIs | MDN
The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for...
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