@testing-library/react#fireEvent TypeScript Examples

The following examples show how to use @testing-library/react#fireEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: test-utils.tsx    From abacus with GNU General Public License v2.0 7 votes vote down vote up
/**
 * Change the value in a form field.
 */
export async function changeFieldByRole(role: string, name: RegExp, value: string) {
  const field = screen.getByRole(role, { name: name })
  // eslint-disable-next-line @typescript-eslint/require-await
  await act(async () => {
    fireEvent.change(field, { target: { value: value } })
  })
}
Example #2
Source File: ConfigureOPNavbar.test.tsx    From one-platform with MIT License 6 votes vote down vote up
describe("ConfigureSSI Page", () => {
  it("should render configure SSI page", () => {
    const { getByText } = render(<ConfigureOPNavbar />);
    const headingElement = getByText(/Configure OPC Base/i);
    expect(headingElement).toBeInTheDocument();
  });

  it("should change active theme", async () => {
    const { container } = render(<ConfigureOPNavbar />);
    let currentActiveImage = container.querySelector("img[active-theme]");
    const navOnlyThemeImage = container.querySelector("#nav-only"); // get the nav-only image button
    expect(currentActiveImage?.getAttribute("active-theme")).toEqual(
      "full-ssi"
    );
    fireEvent.click(navOnlyThemeImage!);

    await waitFor(
      () =>
        // getByRole throws an error if it cannot find an element
        container
          .querySelector("img[active-theme]")!
          .getAttribute("active-theme") === "nav-only"
    );
  });
});
Example #3
Source File: ExperimentsTableAgGrid.test.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
it('should render a table with experiments, allow searching and resetting', async () => {
  const experiments: ExperimentSummary[] = [
    {
      experimentId: 1,
      name: 'First',
      endDatetime: addToDate(new Date(), { days: 14 }),
      ownerLogin: 'Owner',
      platform: Platform.Wpcom,
      startDatetime: new Date(),
      status: Status.Staging,
      description: 'hidden description text',
      analyses: [],
    },
  ]
  const { container } = render(<ExperimentsTableAgGrid experiments={experiments} />)

  expect(container).toMatchSnapshot()

  await changeFieldByRole('textbox', /Search/, 'explat_test')
  expect(container).toMatchSnapshot()

  const resetButton = screen.getByRole('button', { name: /Reset/ })
  fireEvent.click(resetButton)
  expect(container).toMatchSnapshot()
})
Example #4
Source File: LevelRange.test.tsx    From zapquaker with MIT License 6 votes vote down vote up
it('should handle change event', () => {
  const onChangeMock = jest.fn();
  act(() => {
    render(<LevelRange value={1} max={9} onChange={onChangeMock} />, container);
  });
  const input = container.querySelector("input[type='range']");
  expect(input).toBeTruthy();
  if (input) {
    fireEvent.change(input, { target: { value: 5 } });
    expect(onChangeMock).toHaveBeenCalledTimes(1);
  }
});
Example #5
Source File: selection.spec.tsx    From react-final-table with MIT License 6 votes vote down vote up
test('Should be able to select rows', async () => {
  const table = render(<TableWithSelection columns={columns} data={data} />);
  const checkbox = table.getByTestId('checkbox-0') as HTMLInputElement;
  const checkbox2 = table.getByTestId('checkbox-1') as HTMLInputElement;
  const toggleAllButton = table.getByTestId('toggle-all') as HTMLInputElement;

  fireEvent.click(checkbox);
  expect(checkbox.checked).toEqual(true);
  expect(table.getAllByTestId('selected-row')).toHaveLength(1);

  fireEvent.click(checkbox2);
  expect(table.getAllByTestId('selected-row')).toHaveLength(2);

  fireEvent.click(checkbox);
  expect(checkbox.checked).toEqual(false);
  expect(table.queryAllByTestId('selected-row')).toHaveLength(1);

  fireEvent.click(checkbox2);
  expect(checkbox2.checked).toEqual(false);
  expect(table.queryAllByTestId('selected-row')).toHaveLength(0);

  // toggle all
  fireEvent.click(toggleAllButton);
  expect(table.queryAllByTestId('selected-row')).toHaveLength(2);

  // toggle all off
  fireEvent.click(toggleAllButton);
  expect(table.queryAllByTestId('selected-row')).toHaveLength(0);
});
Example #6
Source File: Autocomplete.test.tsx    From Cromwell with MIT License 6 votes vote down vote up
describe('Autocomplete component', () => {

    it("renders search content", async () => {
        render(<Autocomplete
            loader={async () => {
                return [
                    { title: '_test1_', id: 'test1' }
                ]
            }}
            getOptionLabel={(item => item.title)}
            label="Autocomplete_label"
        />);

        await screen.findByText('Autocomplete_label');

        fireEvent.change(document.getElementsByTagName('input')?.[0],
            { target: { value: 'a' } })

        await screen.findByText('_test1_');
    });

})
Example #7
Source File: segmented-button.test.tsx    From keycaplendar with MIT License 6 votes vote down vote up
it("calls onClick callback", () => {
  const cb = jest.fn();
  render(
    <SegmentedButton>
      <SegmentedButtonSegment label="Click me" onClick={cb} />
    </SegmentedButton>
  );
  fireEvent.click(screen.getByText("Click me"));
  expect(cb).toHaveBeenCalledTimes(1);
});
Example #8
Source File: Header.spec.tsx    From space-traveling with MIT License 6 votes vote down vote up
describe('Header', () => {
  beforeAll(() => {
    mockedPush.mockImplementation(() => Promise.resolve());
    const MockedRouterContext = RouterContext as React.Context<unknown>;
    RouterWrapper = ({ children }): JSX.Element => {
      return (
        <MockedRouterContext.Provider
          value={{
            push: mockedPush,
          }}
        >
          {children}
        </MockedRouterContext.Provider>
      );
    };
  });

  it('should be able to render logo', () => {
    render(<Header />);

    screen.getByAltText('logo');
  });

  it('should be able to navigate to home page after a click', () => {
    render(<Header />, {
      wrapper: RouterWrapper,
    });

    const secondLink = screen.getByAltText('logo');

    fireEvent.click(secondLink);

    expect(mockedPush).toHaveBeenCalledWith(
      '/',
      expect.anything(),
      expect.anything()
    );
  });
});
Example #9
Source File: Range.test.tsx    From frontend with GNU General Public License v3.0 6 votes vote down vote up
describe('Range', () => {
  const setup = () => {
    const utils = render(<Range />);
    const input = utils.getByLabelText('range-input');
    return {
      input,
      ...utils,
    };
  };

  test('render default Range component', () => {
    const { getByLabelText } = render(<Range />);
    expect(getByLabelText('range')).toBeInTheDocument();
  });
  test('render Range component with some value', () => {
    const { input } = setup();
    fireEvent.change(input, { target: { value: '50' } });
    expect((input as HTMLInputElement).value).toBe('50');
  });
});
Example #10
Source File: Snackbar.test.tsx    From atlas with GNU General Public License v3.0 6 votes vote down vote up
describe('Snackar', async () => {
  it('Display snackbar', async () => {
    const { getByText } = render(<TestElement />, {
      wrapper: ({ children }) => (
        <BrowserRouter>
          {children}
          <Snackbars />
        </BrowserRouter>
      ),
    })

    fireEvent.click(screen.getByRole('button'))

    getByText(props.title ?? '')
    getByText(props.description ?? '')
    getByText(props.actionText ?? '')

    await waitForElementToBeRemoved(() => getByText(props.title ?? ''))
  })
})
Example #11
Source File: index.test.tsx    From ii-admin-base with MIT License 6 votes vote down vote up
// 测试 Ant Design 的原始 Input 组件是否正常
describe("Test InputVerify component on the props of antd's input component", () => {
  /**
   * 针对多个测试case运行前需获取相同的元素,可以通过beforeEach避免重复设置。
   * 在每个case运行之前,都会运行该函数
   */
  beforeEach(() => {
    wrapper = render(<InputVerify {...antdProps} />);

    // 在元素加上 data-testid
    inputElement = wrapper.getByTestId('test-input-verify') as HTMLInputElement;
  });

  it("should have the input's class of antd", () => {
    expect(inputElement).toBeInTheDocument(); // 判断元素是否在HTML文档中
    expect(inputElement).toHaveClass('ant-input'); // 判断有没有对应的class
  });

  it('should support size', () => {
    expect(inputElement).toHaveClass('ant-input-lg');
  });

  it('should trigger onChange event correctly', () => {
    // 触发 change 事件
    fireEvent.change(inputElement, { target: { value: 'input test' } });
    expect(antdProps.onChange).toHaveBeenCalled();
    expect(inputElement.value).toEqual('input test');
  });
});
Example #12
Source File: GroupDetailModal.tsx    From ppeforfree with GNU General Public License v3.0 6 votes vote down vote up
describe("Expanded DetailModal", () => {
  it("displays name", () => {
    const {getByTestId, getByText} = render(<TestModal />);
    const eyeIcon = getByTestId("eye-icon");

    fireEvent.click(eyeIcon, "click");

    const element = getByText("Group name");
    expect(element).toBeInTheDocument();
  });

  it("displays description", () => {
    const {getByTestId, getByText} = render(<TestModal />);
    const eyeIcon = getByTestId("eye-icon");

    fireEvent.click(eyeIcon, "click");

    const element = getByText("Group description");
    expect(element).toBeInTheDocument();
  });

  it("displays location", () => {
    const {getByTestId, getByText} = render(<TestModal />);
    const eyeIcon = getByTestId("eye-icon");

    fireEvent.click(eyeIcon, "click");

    const element = getByText("Group location");
    expect(element).toBeInTheDocument();
  });
});
Example #13
Source File: SQFormDialog.stories.test.tsx    From SQForm with MIT License 6 votes vote down vote up
it('should not call onClose on `escape` keydown because cancel is not available', async () => {
  render(
    <Default
      isOpen={true}
      onSave={handleSave}
      onClose={handleClose}
      showSecondaryButton={false}
    />
  );

  // fireEvent, not userEvent
  // to confirm the 'key' and 'code' values-- > https://keycode.info/
  // https://testing-library.com/docs/dom-testing-library/api-events/ --> find 'keyboard events'
  fireEvent.keyDown(screen.getByRole('presentation'), {
    key: 'Escape',
    code: 'Escape',
  });

  await waitFor(() => {
    expect(handleClose).not.toHaveBeenCalled();
  });
});
Example #14
Source File: CrystalBall.test.tsx    From ds2020_mauricio with GNU General Public License v3.0 6 votes vote down vote up
test("renders message from backend", async () => {
  // Setup
  axios.get.mockResolvedValue({ data: "message!" });
  act(() => {
    const { getByText } = render(<CrystalBall />);
    fireEvent.click(getByText(/Get My Fortune Told/i));
  });

  // Get results
  const msgElement: any = await waitForElement(() =>
    document.getElementById("msg")
  );
  const text: string = msgElement.innerHTML.valueOf();

  // Assert
  expect(msgElement).toBeInTheDocument();
  expect(text).toContain("message!");
});
Example #15
Source File: SearchInput.test.tsx    From Fashionista with MIT License 6 votes vote down vote up
describe("The component Search Input", () => {
  const mockedProps = {
    value: "",
    onSearchChange: jest.fn(),
  };

  it("Should render Search component", () => {
    render(<SearchInput {...mockedProps} />);
    expect(screen.getByTitle("Pesquisar produto")).toHaveValue("");
  });

  describe("When input changes", () => {
    it("Shoud change the value", () => {
      const onSearchChangeMock = jest.fn();
      render(
        <SearchInput onSearchChange={onSearchChangeMock} value="Vestido" />
      );
      fireEvent.change(screen.getByTitle("Pesquisar produto"), {
        target: { value: "Vestido" },
      });
      expect(screen.getByTitle("Pesquisar produto")).toHaveValue("Vestido");
    });
  });
});
Example #16
Source File: arrow.spec.tsx    From react-carousel with MIT License 6 votes vote down vote up
describe('<Arrow />', () => {
	afterEach(cleanup);

	it('should call onClick prop when click event occurs', async () => {
		const onClick = jest.fn();
		const { getByRole } = render(<Arrow direction="left" onClick={onClick} />);

		fireEvent.click(getByRole('button'));
		expect(onClick).toHaveBeenCalled();
	});
});
Example #17
Source File: index.test.tsx    From ChatUI with MIT License 6 votes vote down vote up
describe('<Popover />', () => {
  it('should not render popover default', () => {
    render(<Test />);

    expect(document.querySelector('.Popover')).not.toBeInTheDocument();
  });

  it('should render popover when active', () => {
    const { getByTestId } = render(<Test />);

    fireEvent.click(getByTestId('btn'));

    expect(document.querySelector('.Popover')).toBeInTheDocument();
  });
});
Example #18
Source File: ArticleEditor.test.tsx    From ts-redux-react-realworld-example-app with MIT License 6 votes vote down vote up
it('Should update article text fields', async () => {
  await act(async () => {
    fireEvent.change(screen.getByPlaceholderText('Article Title'), { target: { value: 'testTitle' } });
    fireEvent.change(screen.getByPlaceholderText("What's this article about?"), {
      target: { value: 'testDescription' },
    });
    fireEvent.change(screen.getByPlaceholderText('Write your article (in markdown)'), {
      target: { value: 'testBody' },
    });
    store.dispatch(updateField({ name: 'tagList', value: 'df' }));
  });

  expect(store.getState().editor.article.title).toMatch('testTitle');
  expect(store.getState().editor.article.description).toMatch('testDescription');
  expect(store.getState().editor.article.body).toMatch('testBody');
});
Example #19
Source File: Invitation.test.tsx    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
describe("Invitation", () => {
  it("Invitation", async () => {
    // MOCK ROUTER https://testing-library.com/docs/example-react-router
    const history = createMemoryHistory();

    const { getByText, queryByTestId } = renderWithStyledTheme(
      <MockedProvider mocks={mocks} addTypename={false}>
        <Router history={history}>
          <AuthProvider>
            <NotificationsWithPortal />
            <Invitation />
          </AuthProvider>
        </Router>
      </MockedProvider>
    );

    history.push("/invitation/" + FAKE_TOKEN);
    expect(queryByTestId("loading")).toBeInTheDocument();
    await wait(0);
    expect(queryByTestId("loading")).not.toBeInTheDocument();
    expect(getByText("AmazingRoom")).toBeInTheDocument();
    expect(getByText(/Anurag Hazra/i)).toBeInTheDocument();
    expect(getByText(/Accept Invitation/i)).toBeInTheDocument();
    expect(history.location.pathname).toBe("/invitation/" + FAKE_TOKEN);

    // ACCEPT
    let button = getByText(/Accept Invitation/i);

    await act(async () => fireEvent.click(button));
    await wait(0);

    // CHECK redirection
    expect(history.location.pathname).toBe("/");
  });
});
Example #20
Source File: AutoresizeTextarea.test.tsx    From hub with Apache License 2.0 6 votes vote down vote up
describe('AutoresizeTextarea', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });

  it('creates snapshot', () => {
    const { asFragment } = render(<AutoresizeTextarea {...defaultProps} />);
    expect(asFragment()).toMatchSnapshot();
  });

  for (let i = 0; i < tests.length; i++) {
    it('renders component', () => {
      render(<AutoresizeTextarea {...defaultProps} value={tests[i].value} />);
      const textarea = screen.getByRole('textbox');
      expect(textarea).toHaveProperty('rows', tests[i].rows);
    });
  }

  it('calls onChange when textarea content is changed', () => {
    render(<AutoresizeTextarea {...defaultProps} />);
    fireEvent.change(screen.getByRole('textbox'), { target: { value: 'text' } });

    expect(mockOnChange).toHaveBeenCalledTimes(1);
  });
});
Example #21
Source File: Button.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
describe('<Button />', () => {
  it('navigates using react-router', async () => {
    const testString = 'This is test string';
    const buttonLabel = 'Navigate!';
    const { getByText } = render(
      wrapInTestApp(
        <Routes>
          <Route path="/test" element={<p>{testString}</p>} />
          <Button to="/test">{buttonLabel}</Button>
        </Routes>,
      ),
    );

    expect(() => getByText(testString)).toThrow();
    await act(async () => {
      fireEvent.click(getByText(buttonLabel));
    });
    expect(getByText(testString)).toBeInTheDocument();
  });
});
Example #22
Source File: feedbackCard.test.tsx    From one-platform with MIT License 5 votes vote down vote up
describe('Feedback Card', () => {
  let component: RenderResult;
  const feedback = mockFeedbacks[0];
  beforeEach(() => {
    component = render(
      <FeedbackCard
        title={feedback.createdBy.cn}
        createdOn={feedback.createdOn}
        description={feedback.summary}
        experience={feedback.experience}
        module={feedback.module}
        category={feedback.category}
        state={feedback.state}
        onClick={mockFn}
      />
    );
  });

  afterEach(() => {
    component.unmount();
  });

  test('Check title is present', () => {
    const textEl = screen.getByText(/lore - 27 January, 2022/i);
    expect(textEl).toBeInTheDocument();
  });

  test('Check popup opens on click', () => {
    const btn = screen.getByText(/view more/i);
    fireEvent.click(btn);
    expect(mockFn.mock.calls.length).toBe(1);
  });

  test('When summary is short ellipsis should  be hidden', () => {
    const textEl = screen.queryByText(/\.\.\./i);
    expect(textEl).toBeNull();
  });

  test('When summary is longer than 200 ellipsis', () => {
    const desc = new Array(300).fill('a').join();
    component.unmount();
    component = render(
      <FeedbackCard
        title={feedback.createdBy.cn}
        createdOn={feedback.createdOn}
        description={desc}
        experience={feedback.experience}
        module={feedback.module}
        category={feedback.category}
        state={feedback.state}
        onClick={mockFn}
      />
    );
    const textEl = screen.getByText(/\.\.\./i);
    expect(textEl).toBeInTheDocument();
  });
});
Example #23
Source File: ExperimentDisableButton.test.tsx    From abacus with GNU General Public License v2.0 5 votes vote down vote up
test('disables an experiment', async () => {
  const experimentReloadRef: React.MutableRefObject<() => void> = { current: jest.fn() }
  const experiment = Fixtures.createExperimentFull()
  const { container } = render(<ExperimentDisableButton {...{ experiment, experimentReloadRef }} />)

  mockedExperimentsApi.changeStatus.mockReset()
  mockedExperimentsApi.changeStatus.mockImplementationOnce(async () => undefined)

  const firstDisableButton = screen.getByRole('button', { name: /Disable/ })

  // First Opening - We cancel
  fireEvent.click(firstDisableButton)

  await waitFor(() => screen.getByRole('button', { name: /Cancel/ }))

  expect(container).toMatchSnapshot()

  const cancelButton = screen.getByRole('button', { name: /Cancel/ })
  fireEvent.click(cancelButton)
  await waitForElementToBeRemoved(cancelButton)

  expect(mockedExperimentsApi.changeStatus).toHaveBeenCalledTimes(0)
  expect(experimentReloadRef.current).toHaveBeenCalledTimes(0)

  // Second Opening - We disable
  fireEvent.click(firstDisableButton)

  await waitFor(() => screen.getByRole('button', { name: /Cancel/ }))
  const cancelButton2nd = screen.getByRole('button', { name: /Cancel/ })

  const allDisableButtons = screen.getAllByRole('button', { name: /Disable/ })
  allDisableButtons.forEach((button) => fireEvent.click(button))

  await waitForElementToBeRemoved(cancelButton2nd)

  expect(mockedExperimentsApi.changeStatus).toHaveBeenCalledTimes(1)
  expect(experimentReloadRef.current).toHaveBeenCalledTimes(1)
  expect(mockedExperimentsApi.changeStatus).toMatchInlineSnapshot(`
    [MockFunction] {
      "calls": Array [
        Array [
          1,
          "disabled",
        ],
      ],
      "results": Array [
        Object {
          "type": "return",
          "value": Promise {},
        },
      ],
    }
  `)
})
Example #24
Source File: filtering.spec.tsx    From react-final-table with MIT License 5 votes vote down vote up
test('Should filter by text', () => {
  const { columns, data } = makeSimpleData();

  const TableWithSearch: FC = () => {
    const { headers, rows, toggleSort, setSearchString } = useTable(
      columns,
      data,
      {
        sortable: true,
      }
    );

    return (
      <>
        <input
          data-testid="input"
          type="text"
          onChange={e => {
            setSearchString(e.target.value);
          }}
        ></input>
        <table>
          <thead>
            <tr>
              {headers.map((header, idx) => (
                <th
                  key={idx}
                  data-testid={`column-${header.name}`}
                  onClick={() => toggleSort(header.name)}
                >
                  {header.label}

                  {header.sorted && header.sorted.on ? (
                    <span data-testid={`sorted-${header.name}`}></span>
                  ) : null}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((row, idx) => (
              <tr data-testid={`row-${idx}`} key={idx}>
                {row.cells.map((cell, idx) => (
                  <td key={idx}>{cell.render()}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </>
    );
  };

  const table = render(<TableWithSearch />);

  const input = table.getByTestId('input');

  expect(getBodyRows(table)).toHaveLength(3);

  fireEvent.change(input, { target: { value: 'Frodo' } });

  expect(getBodyRows(table)).toHaveLength(1);
  let firstRow = getRow(table, 0);
  expect(firstRow.getByText('Frodo')).toBeInTheDocument();

  fireEvent.change(input, { target: { value: '' } });
  expect(table.getByText('Bilbo')).toBeInTheDocument();
  expect(getBodyRows(table)).toHaveLength(3);

  fireEvent.change(input, { target: { value: 'Bag' } });
  expect(getBodyRows(table)).toHaveLength(2);
});