How do I write a test?

I’m trying out JSONforms in a simple React project based on jsonforms-react-seed which works well but I’m stuck trying to write a test. Whatever I try falls foul of the useLayoutEffect warning and I can’t see how to make an assertion that, eg. the form fields are rendered in my form. I found mention of the useLayoutEffect problem here but I don’t understand the solution. I’ve moved from Material renderers to Vanilla hoping that this would avoid the problem but it doesn’t.

Any pointers to examples would be welcome. FWIW my repo is here: https://github.com/FAIMS/FAIMS3-Elaboration/tree/feature/add-main-forms

[original thread by Steve Cassidy]

[Steve Cassidy]

I’ve now found a way to test that a field is rendered but it still triggers the useLayoutEffect warning and the only way I can check the rendered form is by looking at the html string from a shallow render. ie.

[Steve Cassidy]

  const wrapper = shallow(<SchemaForm formSpec={formSpec} callbackFn={callback} />, div);

  expect(wrapper.contains('Next')).toBe(true) // Next button
  expect(wrapper.html()).toMatch(formSpec.schema.properties.foo.title)

We also have some tests were we check the content of a rendered JsonForms component, see for example jsonforms/JsonForms.test.tsx at 08c6b93fe355d454c97bc8e821382a4b08318ab9 · eclipsesource/jsonforms · GitHub. However we use the full mount instead of shallow.

You can ignore the useLayoutEffect warning for now. The layout effect is used for the update event dispatching and therefore doesn’t influence the actual rendering. I hope to get rid of it soon, maybe even with the next release.

[Steve Cassidy]

Thanks, I managed to work out a reasonable test. I’m not sure why I couldn’t get it to work before but now I’m not seeing the useEffect error at all now - I don’t understand why. The switch to using mount over shallow was the main change along with working out how to drive Enzyme.

[Steve Cassidy]

Here’s my test now for reference:

it('renders a simple form', () => {
  const div = document.createElement('div');

  const callback = () => 3

  const wrapper = mount(<SchemaForm formSpec={formSpec} callbackFn={callback} />, div);

  // we have a next button
  expect(wrapper.find('button').text()).toBe("Next") 
  // we have a label with the field name
  expect(wrapper.find('label').text()).toMatch(formSpec.schema.properties.foo.title)
  // we have an input element with the right id
  expect(wrapper.exists('input[id="#/properties/foo-input"]')).toBe(true)
  // value should be empty
  expect(wrapper.find('input[id="#/properties/foo-input"]').props().value).toBe("")

  wrapper.unmount()
});

Looks good!