如何使用玩笑正确地测试蚂蚁设计的Select和Option?

时间:2020-07-10 11:36:08

标签: antd

我正在为选择表单组件使用Ant Design,并且我想测试options的值,因为这些值会根据用户在填充时做出的不同选择而动态变化。

Future<String> getUserLocation(startlat, startlong) async { //other code await //more code; return yourAddressString; }

my-test.spec.js

我在 let questionDropdown await waitFor(() => { questionDropdown = screen.getByRole('combobox', { name: 'Question'}) expect(questionDropdown).toBeDefined() }) fireEvent.click(questionDropdown) // Hoping to test the options after clicking on the select, but I can't find the options element on screen // expect(screen.getByText('question 1')).toBeDefined() // expect(screen.queryAllByRole('option').length).toEqual(2) 中发现了有关如何模拟Select和Options组件的问题。

antd

但是仍然没有运气来测试我的选项。

2 个答案:

答案 0 :(得分:0)

由于您已经如此嘲笑了它,因此您与Select组件的交互应该是

const questionDropdown = await screen.getByRole('combobox', { name: 'Question'});

act(() => {
    fireEvent.change(questionDropdown, { target: value: { CHANGE_VALUE } });
});

要在不模拟的情况下测试Select组件,应该是这样的

const questionDropdown = await screen.getByRole('combobox', { name: 'Question' });

act(() => {
    fireEvent.click(questionDropdown);
});

// basically, you should be able to find the elements of the 
// dropdown after you fire the click even on the select
const questionOneEle = await screen.getByText('question 1');

act(() => {
    fireEvent.click(questionOneEle);
});

// you can consider using jest-dom to run an assertion here
// at the top of your test file -> import '@testing-library/jest-dom'

expect(questionDropdown).toHaveValue(YOUR_EXPECTED_VALUE);

但是,用这种方法进行测试的烦人之处在于,由于antd处理其select组件的方式,所呈现的下拉项存在相当的不透明性,这可能会使调试失败的测试有点困难。

答案 1 :(得分:0)

我添加了a more complete example of a mock for the Ant Design Select component,到目前为止效果很好(在300个单元测试的中间阶段,迁移模拟antd Select)。我将此模拟文件放置在项目src文件夹中的setupTests.js文件中(我正在使用CRA)。

通过这种模拟,您可以测试如下所示的选择选项:

const options = Array.from(mySelect.querySelectorAll('option')).map(o => o.getAttribute('value');
expect(options).toEqual(['value1', 'value2', 'value3'];

expect(mySelect).toHaveValue('selectedValue');

此示例仅获取选项值属性,还可以通过修改textContent中应用的功能来测试map(显示的值)。

要与选择项进行交互,如angkiki所述,您只需要fireEvent.change(mySelect, { target: { value: 'value2' } });,而自react-testing-library takes care of that for you开始就不需要act()了。如果您仍然有关于使用行为的烦人警告的问题,请参阅https://kentcdodds.com/blog/fix-the-not-wrapped-in-act-warning

相关问题