reactjs React测试库-下拉选择未调用函数

3vpjnl9f  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(123)

我的React组件中有一个Ant Design的下拉菜单(下面是合并代码,只显示相关细节):'

<Select
                  data-testid="addCompany"
                  showSearch
                  style={{ width: '100%' }}
                  onChange={(value) =>
                    onAddCompanySelectHandler(periodIndex, value)
                  }
                  placeholder="Add Company"
                  value={companyDropdownValue}
                  options={companyDropdownList}
                />

'
这是我的测试,呈现组件与下拉菜单和模拟comanies传递给它作为 prop :'

const companyDropdownList = companies; //got this from the mock data

describe('Test BaselineItemDetailsEdit component', () => {
  const onAddCompanySelectHandler = jest.fn();

  const editProps = {
    companyDropdownList,
    onAddCompanySelectHandler
 };

it.only('calls add Company from dropdown', async () => {
  render(<Component {...props} />);
  const company = screen.getByText('Company Name');
  userEvent.click(company);
  expect(onAddCompanySelectHandler).toBeCalled();
});

'我似乎可以从下拉菜单中找到公司,但是当点击它时,函数没有被调用。我在这个组件和测试中有其他常规按钮,它们调用模拟函数。
'

● Test ItemDetails component › calls add Company from dropdown

    expect(jest.fn()).toBeCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

       95 |     const company = screen.getByText('Company Name');
       96 |     userEvent.click(company);
    >  97 |     expect(onAddCompanySelectHandler).toBeCalled();
          |                                       ^
       98 |   });
       99 | });
      100 |


'
我尝试调用模拟函数,并期望它被调用。

nhhxz33t

nhhxz33t1#

这就是我如何结束了测试它。需要得到组合框项目与andt下拉菜单第一次

it('calls Company from dropdown', async () => {
userEvent.click(screen.getByTestId('toExpand'));
userEvent.click(screen.getByRole('combobox'));
userEvent.click(screen.getByText('CompanyName'));

expect(onAddCompanySelectHandler).toBeCalledWith(0, 'CompanyName');

});

相关问题