1

so I am trying to test a form which is implemented in react. When I submit a form through jest, I get a different event as when I submit the event through the browser.

The test I am using is this one:

it("shows success message if registering was successful", async () => {
        fetchMock.mockReturnValueOnce(Promise.resolve(new Response("", { status: 200 })));

        const wrapper = render(<Provider store={getStore()}>
            <RegisterComponent/>
        </Provider>);
        const emailTextfield = wrapper.getByPlaceholderText(/[email protected]/i);
        const password = wrapper.getByPlaceholderText(/eingeben/i);
        const firstName = wrapper.getByPlaceholderText(/max/i);
        const lastName = wrapper.getByPlaceholderText(/mustermann/i);
        const retryPassword = wrapper.getByPlaceholderText(/wiederholen/i);
        const privacyPolicy = wrapper.getByRole("checkbox");
        const registerButton = wrapper.getByRole("button");
        fireEvent.change(emailTextfield, { target: { value: "[email protected]" } });
        fireEvent.change(password, { target: { value: "Test1234!" } });
        fireEvent.change(retryPassword, { target: { value: "Test1234!" } });
        fireEvent.change(firstName, { target: { value: "Lukas" } });
        fireEvent.change(lastName, { target: { value: "Germerott" } });
        fireEvent.change(privacyPolicy, { target: { checked: true } });
        fireEvent.click(registerButton);
        const successMessage = await wrapper.findByText(/erfolgreich/i);

        expect(successMessage).toBeTruthy();
    });

So I am mounting the component and fire events for all inputs. The event which is logged is this one:

<ref *1> HTMLFormElement {
      '__reactFiber$sikt1ggzmx': <ref *2> FiberNode {
        tag: 5,
        key: null,
        elementType: 'form',
        type: 'form',
        stateNode: [Circular *1],
        return: FiberNode {
          tag: 0,
          key: null,
          elementType: [Function: RegisterComponent],
          type: [Function: RegisterComponent],
          stateNode: null,
          return: [FiberNode],
          child: [Circular *2],
          sibling: null,
          index: 0,
          ref: null,
          pendingProps: {},
          memoizedProps: {},
          updateQueue: [Object],
          memoizedState: [Object],
          dependencies: [Object],
          mode: 0,
          flags: 0,
          nextEffect: null,
          firstEffect: null,
          lastEffect: null,
          lanes: 0,
          childLanes: 0,
          alternate: [FiberNode],
          actualDuration: 0,
          actualStartTime: -1,
          selfBaseDuration: 0,
          treeBaseDuration: 0,
          _debugID: 10780,
          _debugSource: [Object],
          _debugOwner: null,
          _debugNeedsRemount: false,
          _debugHookTypes: [Array]
        },
        child: FiberNode {
          tag: 11,
          key: null,
          elementType: [Object],
          type: [Object],
          stateNode: null,
          return: [Circular *2],
          child: [FiberNode],
          sibling: null,
          index: 0,
          ref: null,
          pendingProps: [Object],
          memoizedProps: [Object],
          updateQueue: [Object],
          memoizedState: [Object],
          dependencies: [Object],
          mode: 0,
          flags: 0,
          nextEffect: null,
          firstEffect: null,
          lastEffect: null,
          lanes: 0,
          childLanes: 0,
          alternate: [FiberNode],
          actualDuration: 0,
          actualStartTime: -1,
          selfBaseDuration: 0,
          treeBaseDuration: 0,
          _debugID: 10784,
          _debugSource: [Object],
          _debugOwner: [FiberNode],
          _debugNeedsRemount: false,
          _debugHookTypes: [Array]
        },
        sibling: null,
        index: 0,
        ref: null,
        pendingProps: {
          onSubmit: [Function: submit],
          'data-testid': 'formular',
          children: [Object]
        },
        memoizedProps: {
          onSubmit: [Function: submit],
          'data-testid': 'formular',
          children: [Object]
        },
        updateQueue: null,
        memoizedState: null,
        dependencies: null,
        mode: 0,
        flags: 0,
        nextEffect: null,
        firstEffect: null,
        lastEffect: null,
        lanes: 0,
        childLanes: 0,
        alternate: FiberNode {
          tag: 5,
          key: null,
          elementType: 'form',
          type: 'form',
          stateNode: [Circular *1],
          return: [FiberNode],
          child: [FiberNode],
          sibling: null,
          index: 0,
          ref: null,
          pendingProps: [Object],
          memoizedProps: [Object],
          updateQueue: null,
          memoizedState: null,
          dependencies: null,
          mode: 0,
          flags: 0,
          nextEffect: null,
          firstEffect: [FiberNode],
          lastEffect: [FiberNode],
          lanes: 0,
          childLanes: 1,
          alternate: [Circular *2],
          actualDuration: 0,
          actualStartTime: -1,
          selfBaseDuration: 0,
          treeBaseDuration: 0,
          _debugID: 10782,
          _debugSource: [Object],
          _debugOwner: [FiberNode],
          _debugNeedsRemount: false,
          _debugHookTypes: null
        },
        actualDuration: 0,
        actualStartTime: -1,
        selfBaseDuration: 0,
        treeBaseDuration: 0,
        _debugID: 10782,
        _debugSource: {
          fileName: '/Users/lukasgermerott/Dev/flundr/clientnew/src/components/Register.tsx',
          lineNumber: 61,
          columnNumber: 12
        },
        _debugOwner: FiberNode {
          tag: 0,
          key: null,
          elementType: [Function: RegisterComponent],
          type: [Function: RegisterComponent],
          stateNode: null,
          return: [FiberNode],
          child: [Circular *2],
          sibling: null,
          index: 0,
          ref: null,
          pendingProps: {},
          memoizedProps: {},
          updateQueue: [Object],
          memoizedState: [Object],
          dependencies: [Object],
          mode: 0,
          flags: 0,
          nextEffect: null,
          firstEffect: null,
          lastEffect: null,
          lanes: 0,
          childLanes: 0,
          alternate: [FiberNode],
          actualDuration: 0,
          actualStartTime: -1,
          selfBaseDuration: 0,
          treeBaseDuration: 0,
          _debugID: 10780,
          _debugSource: [Object],
          _debugOwner: null,
          _debugNeedsRemount: false,
          _debugHookTypes: [Array]
        },
        _debugNeedsRemount: false,
        _debugHookTypes: null
      },
      '__reactProps$sikt1ggzmx': {
        onSubmit: [Function: submit],
        'data-testid': 'formular',
        children: {
          '$$typeof': Symbol(react.element),
          type: [Object],
          key: null,
          ref: null,
          props: [Object],
          _owner: [FiberNode],
          _store: {}
        }
      }
    }

But when I log the same event in the browser I am getting this one

<form>
   <div class=​"MuiGrid-root MuiGrid-container MuiGrid-spacing-xs-2 MuiGrid-direction-xs-column">
      <div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
      <h5 class=​"MuiTypography-root MuiTypography-h5">​Registration​</h5>
   </div>
   <div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
   <p class=​"MuiTypography-root MuiTypography-body1">​Persönliche Daten​</p>
   </div>​
   <div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
   <div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
   <div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
   <div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
   <div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
   <div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
   <div class=​"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12">​…​</div>
   </div>​
</form>

This is right because now I can access the values through the event. My onsubmit function is the following:

function submit(event: React.SyntheticEvent) {
        event.preventDefault();
        // Create target object to extract information from
        const target = event.target as typeof event.target & {
            email: { value: string };
            firstName: { value: string };
            lastName: { value: string };
            privacyPolicy: { checked: boolean };
          };
        console.log(target, "TARGET");
        const user : IUserRegistrationModel = {
            email: target.email.value,
            firstName: target.firstName.value,
            lastName: target.lastName.value,
            password: password,
            privacyPolicy: target.privacyPolicy.checked,
        };
        dispatch(authActions.register(user));
    }

The Problem in the test is: When it submits the event, it cant extract the values from the event and simply crashes. With the browser event it works fine.

Do you guys have an idea?

Edit: Reproduced example https://codesandbox.io/s/brave-goldberg-8hfri?file=/src/App.tsx

5
  • Do you get any errors from the test? Have you tried logging the user object to see if you get the expected result in the test? Commented Feb 24, 2021 at 16:40
  • Are you able to reproduce this example in codesandbox.io ? Commented Feb 24, 2021 at 16:41
  • I get errors. It says that Cannot read property 'value' of undefined. Let me try to reproduce this. Commented Feb 24, 2021 at 16:42
  • related/duplicate of this stackoverflow.com/a/61537739/1980235 ? Commented Feb 24, 2021 at 16:45
  • So guys, I made a codesandbox codesandbox.io/s/brave-goldberg-8hfri?file=/src/App.tsx Commented Feb 24, 2021 at 17:00

1 Answer 1

2

It's a duplicate of this one: https://stackoverflow.com/a/61537739/1980235

The problem you have it with trying to access the input directly from event.target. You should access it from event.target.elements instead: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements.

Based on the given sandbox, I was able to get the tests passing by updating the following code:

function onSubmit(event: React.SyntheticEvent<HTMLFormElement>) {
  event.preventDefault();
  // Create target object to extract information from
  const payload = event.currentTarget.elements as typeof event.currentTarget.elements & {
    email: { value: string };
  };
  console.log(payload.email.value);
  setShow(true);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.