【问题标题】:How to test a react dropdown form如何测试反应下拉表单
【发布时间】:2021-08-24 18:56:13
【问题描述】:

我是测试 React 组件的新手,我正在努力增加对我的一个组件的覆盖率。目前我有非常基本的测试,只是确保渲染和匹配快照,但为了增加覆盖率,我想添加一个点击事件,将下拉表单选项更改为表单中的另一个选项。 I want to click foo and have the dropdown open and i can click bar.

describe("DropdownForm", () => {
    let wrapper;
    beforeEach(() => {
        wrapper = shallow(<DropdownForm choices={choices} label={label} />);
    });
    it("should match snapshot", () => {
        expect(wrapper).toMatchSnapshot();
    });
    it("should list the number of dropdown options", () => {
        expect(wrapper.find("option").length).toEqual(3);
    });
    it("should click on the dropdown menu", async () => {
        const dropdownForm = getByText("foo");
        fireEvent.click(dropdownForm);
        const option = await waitForElement(() => getBytext("bar"), {
            wrapper
        });
        fireEvent.click(option);
        expect(handleOnChange).toHaveBeenCalledTimes(1);
    });
});

这是一个 sn-p,显然最后一个测试不起作用,说 foo 找不到,我只是卡住了,不确定我能做些什么来增加覆盖率。

【问题讨论】:

    标签: javascript reactjs react-component


    【解决方案1】:

    试试这个方法:

    const component = mount(<MyComponent/>);
    component.find('#dropdown').at(0).simulate('change', {
        target: { value: 'item1', name: 'item1' }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 2021-07-12
      相关资源
      最近更新 更多