1

我正在尝试模拟一个反应选择组件,以便在测试触发事件中使用它。下面是我使用 jest 创建的反应选择。

jest.mock("react-select", () => ({ options, onChange }) => {
  function handleChange(event) {
    const option = [];
    option.push(options.find(option => option === event.currentTarget.value));
    onChange(option);
    console.log(option);............................................................//line 1
  }
  return (
    <select
      data-testid="test-select"
      name="users"
      label="users"
      options={[
        "a",
        "b",
        "c",
        "d",
        "e"
      ]}
      onChange={handleChange}
    >
      {options.map(value => (
        <option key={value} value={value}>
          {value}
        </option>
      ))}
    </select>
  );
});

问题是控制台在控制台中line 1打印未定义。下面是我测试的火灾事件模型:

const chooseInput = getByTestId("test-select");
    fireEvent.change(chooseInput, {
      target: {
        value: "b"
      }
    });

测试失败为:

expect(received).toBeInTheDocument()

    received value must be an HTMLElement or an SVGElement.
    Received has value: null

为什么在火灾事件发生时该选项没有更新?

4

1 回答 1

0

从库中模拟默认导出的结构是:

jest.mock("react-select", () => {
  return {
    __esModule: true,
    default: ({ options, onChange }) => {
      // Your mock implementation goes here
    },
  };
})

__esModule: true重要

主函数需要返回一个具有default代表您的模拟实现的属性的对象

所以完整的代码应该是

jest.mock("react-select", () => {
  return {
    __esModule: true,
    default: ({
      options,
      onChange
    }) => {
      function handleChange(event) {
        const option = [];
        option.push(options.find(option => option === event.currentTarget.value));
        onChange(option);
        console.log(option);
      }
      return ( <
        select data - testid = "test-select"
        name = "users"
        label = "users"
        options = {
          [
            "a",
            "b",
            "c",
            "d",
            "e"
          ]
        }
        onChange = {
          handleChange
        } > {
          options.map(value => ( <
            option key = {
              value
            }
            value = {
              value
            } > {
              value
            } <
            /option>
          ))
        } <
        /select>
      );
    },
  };
})
于 2020-04-12T10:23:42.830 回答