Home > OS >  react testing give inputs fake values
react testing give inputs fake values

Time:10-02

Beginner on react testing, here i have a form where adding new camera with its test.

My question: is there a way to target 'AddName' give it a fake value and then continue with fireEvent.change to edit that value/change it ?

Because my inputs are not getting any initial values at the moment, i want to test it this way to know if those inputs had value then user can edit them. thats why i want to give inputs fake value in test file then change those. English is not my mother language so could be mistakes.

test code:

import React from "react";
import {
  render,
  screen,
  RenderResult,
  cleanup,
  fireEvent,
  getByRole,
  getByDisplayValue,
} from "@testing-library/react";

const onFormSubmit = jest.fn();
const currentCamera = "0-0-0-2";

describe("Testing component", () => {
  const AddCamera = () =>
    render(
      <Provider store={store}>
        <MemoryRouter>
          <CameraForm onSubmit={onFormSubmit} key={"cameraform-"   currentCamera} />
        </MemoryRouter>
      </Provider>
    );

  test("Testing Add Camera", () => {
    AddCamera();

    const stateBeforeAdd = {
      cameras: [
        {
          identifier: "0-0-0-2",
          name: "Camera 1",
        },
      ],
    };

    const AddName = screen.getByTestId(/^AddName/i);

    expect(AddName).toBeInTheDocument();
    fireEvent.change(AddName, { target: { value: "Camera 2" } });
    expect(AddName).toHaveValue("Camera 2");

    const resultingStateAfterAdd = {
      cameras: [
        {
          identifier: "0-0-0-2",
          name: "Camera 1",
        },
        {
          identifier: "0-0-0-2",
          name: "Camera 2",
        },
      ],
    };

    expect(
      reducers.camReducer(stateBeforeAdd, {
        type: ActionType.ADD_CAMERA,
        payload: {
          identifier: "0-0-0-2",
          name:AddName.value,
        },
      })
    ).toEqual(resultingStateAfterAdd);
  });
});

form:

import {
  Box,
  Button,
  TextField,
  FormControl,
  MenuItem,
  FormGroup,
  Select,
  InputLabel,
} from "@material-ui/core/";

const renderAdd = () => {
    const { helperText, error, name } = state;
    return (
      <React.Fragment>
        <Box sx={boxStyle}  data-testid="CameraForm">
          <form
            data-testid="renderAddForm"
            onSubmit={handleSubmit}>
            <div className="handle">
              <Box>
                <Button
                  onClick={nulll}
                  aria-label="close-settings-popup">
                  <Close />
                </Button>
              </Box>
            </div>
            <div>
              <FormGroup>
                <Box>
                  <FormControl>
                    <TextField
                      helperText={helperText.name}
                      error={error.name}
                      inputProps={{
                        "data-testid": "AddName",
                      }}
                      InputProps={{
                        className: classes.underline,
                      }}
                      InputLabelProps={{
                        className: classes.inputLabelColor,
                      }}
                      required={true}
                      type="text"
                      id="name"
                      value={name}
                      onChange={handleChange}
                      label='Name'
                    ></TextField>
                  </FormControl>
                </Box>
              </FormGroup>
            </div>
            {!state.readOnly ? (
              <div>
                <Button
                  // style={{ flex: "1" }}
                  onClick={nulll}
                  variant="outlined">
                  Cancel
                </Button>
                <Button
                  data-testid="submitButton"
                  type="submit"
                  variant="contained"
                  color="primary"
                  disabled={
                    !currentSite ||
                    Object.values(state.error).some((v) => {
                      return v === true;
                    })
                  }
                  className={classes.button_basic}
                  startIcon={<Done />}
                >
               Accept
                </Button>
              </div>
            ) : (
              ""
            )}
          </form>
        </Box>
      </React.Fragment>
    );
  };

CodePudding user response:

You can simulate user input on a text field by importing this:

import userEvent from '@testing-library/user-event';

Then simulate typing with:

const inputEl = screen.getByTestId("AddName");
userEvent.type(inputEl, "SOME TEXT TO TYPE");
  • Related