11

您好,我正在尝试测试使用 Material-UI 创建的 Slider 组件,但我无法通过测试。我想使用fireEventwith测试值的变化@testing-library/react。我一直在关注这篇文章以正确查询 DOM,但我无法获得正确的 DOM 节点。

提前致谢。

<Slider />零件

// @format
// @flow

import * as React from "react";
import styled from "styled-components";
import { Slider as MaterialUISlider } from "@material-ui/core";
import { withStyles, makeStyles } from "@material-ui/core/styles";
import { priceRange } from "../../../domain/Search/PriceRange/priceRange";

const Wrapper = styled.div`
  width: 93%;
  display: inline-block;
  margin-left: 0.5em;
  margin-right: 0.5em;
  margin-bottom: 0.5em;
`;

// ommited code pertaining props and styles for simplicity

function Slider(props: SliderProps) {
  const initialState = [1, 100];
  const [value, setValue] = React.useState(initialState);

  function onHandleChangeCommitted(e, latestValue) {
    e.preventDefault();
    const { onUpdate } = props;
    const newPriceRange = priceRange(latestValue);
    onUpdate(newPriceRange);
  }

  function onHandleChange(e, newValue) {
    e.preventDefault();
    setValue(newValue);
  }

  return (
    <Wrapper
      aria-label="range-slider"
    >
      <SliderWithStyles
        aria-labelledby="range-slider"
        defaultValue={initialState}
        // getAriaLabel={index =>
        //   index === 0 ? "Minimum Price" : "Maximum Price"
        // }
        getAriaValueText={valueText}
        onChange={onHandleChange}
        onChangeCommitted={onHandleChangeCommitted}
        valueLabelDisplay="auto"
        value={value}
      />
    </Wrapper>
  );
}

export default Slider;

Slider.test.js

// @flow

import React from "react";
import { cleanup,
  render,
  getAllByAltText,
  fireEvent,
  waitForElement } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";

import Slider from "../Slider";


afterEach(cleanup);

describe("<Slider /> specs", () => {

  // [NOTE]: Works, but maybe a better way to do it ?
  xdescribe("<Slider /> component aria-label", () => {

    it("renders without crashing", () => {
      const { container } = render(<Slider />);
      expect(container.firstChild).toBeInTheDocument(); 
    });
  });

  // [ASK]: How to test the event handlers with fireEvent.
  describe("<Slider /> props", () => {

    it("display a initial min value of '1'", () => {
      const renderResult = render(<Slider />);
      // TODO
    });

    it("display a initial max value of '100'", () => {
      const renderResult = render(<Slider />);
      // TODO
    });

    xit("display to values via the onHandleChangeCommitted event when dragging stop", () => {
      const renderResult = render(<Slider />);
      console.log(renderResult)
      // fireEvent.change(renderResult.getByText("1"))
      // expect(onChange).toHaveBeenCalled(0);
    });

    // [NOTE]: Does not work, returns undefined
    xit("display to values via the onHandleChange event when dragging stop", () => {
      const renderResult = render(<Slider />);

      console.log(renderResult.container);
      
      const spanNodeWithAriaAttribute = renderResult.container.firstChild.getElementsByTagName("span")[0].getAttribute('aria-label')
      expect(spanNodeWithAriaAttribute).toBe(/range-slider/)
    });
  });

  // [ASK]: Works, but a snapshot is an overkill a better way of doing this ?
  xdescribe("<Slider /> snapshot", () => {

    it("renders without crashing", () => {
      const { container } = render(<Slider />);
      expect(container.firstChild).toMatchSnapshot();
    });
  });
});
4

4 回答 4

5

经过几个小时的斗争,我能够解决与测试 MUI 滑块相关的案例

这真的取决于你需要如何测试你的,在我的情况下,我必须检查标签文本内容是否在使用marks滑块道具单击标记后发生了变化。

问题

1)slider组件根据元素计算返回值,getBoundingClientRect并且MouseEvent

2)如何查询slider和触发事件。

3)JSDOM对读取元素实际高度和宽度的限制导致问题1

解决方案

1) mockgetBoundingClientRect也应该解决问题 3

2)将测试ID添加到滑块并使用使用fireEvent.mouseDown(contaner, {....})

const sliderLabel = screen.getByText("Default text that the user should see")

// add data-testid to slider
const sliderInput = screen.getByTestId("slider")

// mock the getBoundingClientRect
    sliderInput.getBoundingClientRect = jest.fn(() => {
      return {
        bottom: 286.22918701171875,
        height: 28,
        left: 19.572917938232422,
        right: 583.0937919616699,
        top: 258.22918701171875,
        width: 563.5208740234375,
        x: 19.572917938232422,
        y: 258.22918701171875,
      }
    })

    expect(sliderInput).toBeInTheDocument()

    expect(sliderLabel).toHaveTextContent("Default text that the user should see")
    await fireEvent.mouseDown(sliderInput, { clientX: 162, clientY: 302 })
    expect(sliderLabel).toHaveTextContent(
      "New text that the user should see"
    )

于 2020-06-07T03:53:33.047 回答
4

我建议不要为自定义组件编写测试,并相信该组件适用于我们所有的案例。

通读这篇文章了解更多详情。他们已经提到如何为包装的组件编写单元测试react-select

我遵循了类似的方法并为我的第三方滑块组件编写了一个模拟。

setupTests.js

jest.mock('@material-ui/core/Slider', () => (props) => {
  const { id, name, min, max, onChange, testid } = props;
  return (
    <input
      data-testid={testid}
      type="range"
      id={id}
      name={name}
      min={min}
      max={max}
      onChange={(event) => onChange(event.target.value)}
    />
  );
});

使用这个模拟,您可以像这样在测试中简单地触发更改事件:

fireEvent.change(getByTestId(`slider`), { target: { value: 25 } });

确保将适当testid的道具作为道具传递给您的SliderWithStyles组件

于 2020-05-06T06:32:50.987 回答
3

我把上面提到的解决方案变成了简单的(Typescript)助手

export class Slider {
  private static height = 10

  // For simplicity pretend that slider's width is 100
  private static width = 100

  private static getBoundingClientRectMock() {
    return {
      bottom: Slider.height,
      height: Slider.height,
      left: 0,
      right: Slider.width,
      top: 0,
      width: Slider.width,
      x: 0,
      y: 0,
    } as DOMRect
  }

  static change(element: HTMLElement, value: number, min: number = 0, max: number = 100) {
    const getBoundingClientRect = element.getBoundingClientRect
    element.getBoundingClientRect = Slider.getBoundingClientRectMock
    fireEvent.mouseDown(
        element,
        {
            clientX: ((value - min) / (max - min)) * Slider.width,
            clientY: Slider.height
        }
    )
    element.getBoundingClientRect = getBoundingClientRect
  }
}

用法:

Slider.change(getByTestId('mySlider'), 40) // When min=0, max=100 (default)
// Otherwise
Slider.change(getByTestId('mySlider'), 4, 0, 5) // Sets 4 with scale set to 0-5
于 2020-07-09T17:16:00.220 回答
0

基于@rehman_00001 的回答,我为组件创建了一个文件模拟。我用 TypeScript 编写了它,但没有类型它应该也能正常工作。

__mocks__/@material-ui/core/Slider.tsx

import { SliderTypeMap } from '@material-ui/core';
import React from 'react';

export default function Slider(props: SliderTypeMap['props']): JSX.Element {
    const { onChange, ...others } = props;
    return (
        <input
            type="range"
            onChange={(event) => {
                onChange && onChange(event, parseInt(event.target.value));
            }}
            {...(others as any)}
        />
    );
}

现在,Material UI<Slider/>组件的每次使用都将在测试期间呈现为一个简单的 HTML<input/>元素,使用 Jest 和react-testing-library.

{...(others as any)}是一个 hack,让我不必担心确保原始组件的每个可能的道具都得到正确处理。根据您所依赖的道具,您可能需要在解构过程中提取额外的道具,以便您可以正确地将它们转换为对香草元素Slider有意义的东西。有关每个可能属性的信息,请参阅 Material UI 文档中的此页面。<input/>

于 2021-06-25T16:40:00.647 回答