Solvedant design Impossible to expand Select component dropdown programatically

  • I have searched the issues of this repository and believe that this is not a duplicate.

Reproduction link

https://codepen.io/martis347/pen/XWbVPap?editors=0010

Steps to reproduce

Try to programatically expand element, to see the dropdown in one of these ways:

document.querySelector('.ant-select').click()
document.querySelector('.ant-select-selector').click()
document.querySelector('.ant-select-selection-search').click()
document.querySelector('input').click()

What is expected?

Select would expand and show dropdown values.

What is actually happening?

Select is not expanding. The only possible way to expand it that I found is by using your mouse.

Environment Info
antd 4.0.2
React 16.13.0
System Windows 10
Browser Google Chrome 80.0.3987.132 (Official Build) (64-bit)

This used to work in Ant design 3.x.x but seems to be broken now after updating to ant design 4.0.2.

17 Answers

✔️Accepted Answer

@martis347 Propably it's mousedown event now instead of click.

I was able to open antd v4 select with the code below (tested in chrome console):

let select = document.querySelector('.ant-select-selector');
let clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent('mousedown', true, true);
select.dispatchEvent(clickEvent)

Edit: Tested with RTL, works like a charm. Calling fireEvent.mouseDown on .ant-select-selector should open antd select in unit tests @Meshour :)

Tested with:

const select = container.querySelector(
    '[data-testid=mcc-select] > .ant-select-selector'
);
fireEvent.mouseDown(select); // this should open select in unit tests

Other Answers:

I managed to test clicking and selecting multiple options and then expect the page results to change.

      const { findAllByText } = setup();

      const select= document.querySelector(
        `[data-testid="<test_id>"] > .ant-select-selector`
      ) as HTMLElement;

      // click on the select input 
      fireEvent.mouseDown(select);

      // wait for the ant dropdown element to appear
      await waitFor(() => {
        return expect(
          document.querySelector(".ant-select-dropdown")
        ).toBeInTheDocument();
      });

      // select a single dropdown option
      fireEvent.click(document.querySelector(`[label="1"]`) as Element)

      const records = await findAllByText(/record/);
      expect(records).toHaveLength(1);
      
      // select another dropdown option
      fireEvent.click(document.querySelector(`[label="2"]`) as Element)

      const records2 = await findAllByText(/record/);
      expect(records2).toHaveLength(2);

I spent hours on this, so I hope it helps someone :)

Thanks @mrdannael, I have lost so much time with this. Here are some more details:

You can select your component like so to avoid the querySelector all

const elt = getByTestId('your-test-id').firstElementChild;
fireEvent.mouseDown(elt);

Now at this point you probably want to select an option from the list but there is an animation going on so the following code (that used to work in v3) will fail.

expect(getByText('Option from Select')).toBeVisible(); // FAILS !

You have 2 options, use toBeInTheDocument() or wait for the animation to be over by using waitFor(...)

Option 1: Faster but not totally accurate, I prefer to use this for simple use cases as it makes the tests faster and synchronous

expect(getByText('Option from Select')).toBeInTheDocument(); // WORKS !

Option 2: Slower as you need to wait for the animation to finish but more accurate for complex cases

await waitFor(() => expect(getByText('Option from Select')).toBeVisible()); // WORKS !

Hi guys, its impossible to test Select and Autocompletes components.

Here it's my unit test using jest and testing library.

import React from 'react'
import faker from 'faker'
import { Form } from 'antd'
import { fireEvent, render, screen, RenderResult, waitFor } from '@testing-library/react'
import { BankAutocompleteInput } from '@/shared/presentation/components'
import { FormContext } from '@/shared/presentation/contexts'

const makeSut = (fieldName: string): RenderResult => {
  return render(
    <FormContext.Provider value={{ state: {} }}>
      <Form>
        <BankAutocompleteInput
          name={fieldName}
        />
      </Form>
    </FormContext.Provider>
  )
}

describe('BankAutocompleteInput Component', () => {
  beforeAll(() => {
    Object.defineProperty(window, 'matchMedia', {
      writable: true,
      value: jest.fn().mockImplementation(query => ({
        matches: false,
        media: query,
        onchange: null,
        addListener: jest.fn(), // Deprecated
        removeListener: jest.fn(), // Deprecated
        addEventListener: jest.fn(),
        removeEventListener: jest.fn(),
        dispatchEvent: jest.fn(),
        setState: jest.fn()
      }))
    })
  })

  test('Should set value on combobox click', async () => {
    const field = faker.database.column()
    makeSut(field)

    const input = screen.getByTestId(field).firstElementChild
    fireEvent.mouseDown(input)
    await waitFor(() => fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Banco do Brasil S.A.' } }))

    await waitFor(() => fireEvent.click(document.querySelectorAll('.ant-select-item-option-content')[0]))

    expect(screen.getByRole('combobox')).toHaveValue('001')
  })
})

I'm receiving this error on terminal, but the unit tests is passing on green.

   Console

    console.error
      Warning: An update to List inside a test was not wrapped in act(...).
      
      When testing, code that causes React state updates should be wrapped into act(...):
      
      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */
      
      This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
          in List (created by OptionList)
          in OptionList (created by ForwardRef(Select))
          in div (created by SelectTrigger)
          in div (created by Align)
          in Align (created by CSSMotion)
          in DomWrapper (created by CSSMotion)
          in CSSMotion (created by PopupInner)
          in PopupInner (created by Popup)
          in div (created by Popup)
          in Popup (created by Trigger)
          in ForwardRef (created by Trigger)
          in Trigger (created by SelectTrigger)
          in SelectTrigger (created by ForwardRef(Select))
          in div (created by ForwardRef(Select))
          in ForwardRef(Select) (created by Select)
          in Select (created by ForwardRef(InternalSelect))
          in ForwardRef(InternalSelect) (created by Context.Consumer)
          in ForwardRef(AutoComplete) (created by Field)
          in Unknown
          in Unknown (created by Field)
          in div (created by FormItemInput)
          in div (created by FormItemInput)
          in div (created by Col)
          in Col (created by FormItemInput)
          in FormItemInput (created by Field)
          in div (created by Row)
          in Row (created by Field)
          in Field (created by WrapperField)
          in WrapperField (created by FormItem)
          in FormItem (created by BankAutoCompleteInput)
          in BankAutoCompleteInput
          in form (created by ForwardRef(Form))
          in ForwardRef(Form) (created by ForwardRef(InternalForm))
          in SizeContextProvider (created by ForwardRef(InternalForm))
          in ForwardRef(InternalForm)

      at printWarning (node_modules/react-dom/cjs/react-dom.development.js:88:30)
      at error (node_modules/react-dom/cjs/react-dom.development.js:60:5)
      at warnIfNotCurrentlyActingUpdatesInDEV (node_modules/react-dom/cjs/react-dom.development.js:23284:7)
      at dispatchAction (node_modules/react-dom/cjs/react-dom.development.js:15656:9)
      at node_modules/rc-virtual-list/lib/hooks/useHeights.js:61:7

How i can test this without warnings?

Thanks forwards.

Related Issues:

431
ant design How to set 100% of height layout
This works for me: <Layout style={{height:100vh}}> I am a newbie I base on Meteor JS How to set 100%...
413
ant design Each record in table should have a unique key prop,or set rowKey to an unique primary key.
@ahmetkuslular The error message is pretty explicit your data set must contain items with a key prop...
153
ant design 😨 Table align broken when cell contains long number or long word after 3.11.3
超长连续字段(长数字和长单词) 破坏表格布局的问题(即使你指定了列的宽度也会被挤开),之前组件内默认加过 word-break: break-word; 去纠正此类布局,又会引起 #13624 的问题...
119
ant design Can't set form initialValues from state
I had the same problem sometimes the initialValues are empty and I need to fetch the initialValues f...
113
ant design CheckBox with Form was not work
I ran in to similar problem when i was trying to send form with selected checkbox because function v...
93
ant design import the antd theme, webpack build show .bezierEasingMixin error ?
version: antd@2.x less@2.x 是OK的。 less@3.x,需要开启 配置项 javascriptEnabled: true 但依然有错误: ...
81
ant design Check Box Validation not working
Following @yesmeck 's suggestion I came up with the following code which works as well ...
78
ant design Customization of theme is broken with latest version of less-loader
#23603 #23596 less-loader@5 less-loader@6 I have searched the issues of this repository and believe ...
59
ant design 引用国际化包报错
Change to fix this problem The resource provided by the document is wrong. I have searched the issue...
58
ant design Is there any way to disable all animations?
If anyone is wondering how to get rid of this clicked (glow fade-out) animation: Depending on the An...
38
ant design error TS2605 JSX element type Button is not a constructor function for JSX elements
Do you have allowSyntheticDefaultImports: true in tsconfig.json? Hello since this morning I am getti...
29
ant design Type error: Cannot find name 'ResizeObserver'.
The temporary fix is putting following interface to your typings/index.d.ts: I have searched the iss...
27
ant design Flash of unstyled content for first load
There is also a 'flash' of content reflow apparent on https://ant.design/components/layout/ - have a...
23
ant design Select Custom dropdown with dropdownRender property not respond to click
Another perhaps more elegant I have searched the issues of this repository and believe that this is ...
22
ant design Impossible to expand Select component dropdown programatically
@martis347 Propably it's mousedown event now instead of click I have searched the issues of this rep...
22
ant design Errors when importing antd.less using less-loader
You mean less@3.0.0-alpha.3? Could you try less@2.7.2? Version antd @2.13.4 webpack @3.6.0 less @3.0...
19
ant design Typing issues with Typescript 3 and new LibraryManagedAttributes feature
For me the workaround is adding skipLibCheck: true to tsconfig.json https://stackoverflow.com/a/5240...
18
ant design Webpack css loading
This issue is resolved for me when i remove part of the recommended .babelrc config for ant-design B...
18
ant design Menu.Item should have the onClick param
NOTE: Please click the thumb up (👍) rather than '+1' comment Wrapping with <a> works fine but I thi...
17
ant design Integrating with react-boilerplate
I found a workaround but I don't know why yet The dot can't existed in JSX expression for production...
17
ant design Equal height items
Using flexbox-enabled rows with type=flex and setting the height to 100% on the column contents work...
16
ant design useForm > getFieldValue does not work
In addition to this I also noticed that getFieldValue which is supposed to listen to field value cha...
14
ant design Button tsd error in latest typescript@3.4.2
Same here But I bypassed the problem by downgrading @types/react to 16.8.11 I think it breaks in bot...
14
ant design Long list optimization
SuperSelect is based on antd Select which supports a virtual list of tens of thousands of data the s...
13
ant design form demo element id not unique
@zhutiancheng2 给 Form 加个 name 就行了。react-component/form#197 Please add name to different Form: ...
12
ant design Add .focus .blur method for every form control components
@ChuckJonas That's exactly the problem Most of you probably want to really focus and open the rc-sel...
12
ant design Property 'value' does not exist on type 'EventTarget'.
See DefinitelyTyped/DefinitelyTyped#12239 you can try event.currentTarget. Version 2.12.1 Environmen...
12
ant design Table onRow Event multiple triggered
Perfect!!! It works with: Thanks a lot @yesmeck !!! Version 3.1.0 Environment macos 10.12.6 ...
9
ant design Menu.SubMenu SubMenu.js:452 Uncaught TypeError: Illegal invocation
Could you remove node_modules and package-lock.json(or yarn.lock) then try again? ...
5
ant design TS2304: Cannot find name 'PropertyKey'.
Because PropertyKey is in es2015 library so you should included es2015 in the compilation add lib op...
4
ant design How to make nested table show different data in different rows?
What problem does this feature solve? At parent table's rows there are different data in nested tabl...
8
ng zorro antd 9.0.0-beta.2 Fails to compile
Same problem with beta.3 and angular 9.1 but on many more components ng-zorro-antd/* A small extract...
4
ant design pro 🐛[BUG] Login doesn't work properly if /api/currentUser route is protected
I can also confirm that I've been hit by this It's much simpler to reproduce also ...
3
ant design mobile antd-mobile does not contain an export
Same issue occurred when I executed yarn build Version 1.1.3 Environment react (web browsers) Reprod...
8
slider How do I reset values for slider
No your first fiddle is still a uncontrolled component I have a slider as below which uses marks for...
397
material ui Module not found: Can't resolve 'material-ui-icons/Menu' Martial Next
For anyone else experiencing this issue: npm install @material-ui/icons https://www.npmjs.com/packag...
175
storybook Webpack 4 support?
I'm getting the below error when running Storybook with a project using Webpack 4; This is preventin...
116
material ui Working with react-hook-form
I have added the waiting for users upvotes tag I'm closing the issue as we are not sure people are l...
111
material ui @material-ui/styles: Usage in a Class Component?
i used withStyles instead of makeStyle like this... How does one use the makeStyles API within a cla...
111
storybook babelHelpers is not defined using Rollup [Solved]
@alejandronanez you can remove external-helpers from your .babelrc file and enable it back only on y...
107
material ui Unable to install @mui/material-icons last version
I found a solution here : yarnpkg/yarn#4890 (comment) So either install it using yarn add @mui/mater...
100
material ui theme.spacing is not a function with @material-ui/[styles/core] 4.0.1
Sorry I found the problem Trying to fix another issue today I tried to reset my whole Material-UI 4....
97
material ui Convert ListItem compatible with react-router
This is covered in the documentation: https://material-ui.com/components/buttons/#third-party-routin...
80
material ui Can we add new property for color in palette in MuiTheme
@davidcalhoun Yes you are right this issue is about extending the Button implementation so people ca...
79
storybook Storybook doesn't work with the newest version 10.0.1 of PostCSS Autoprefixer plugin
I also get the same issue as @matamatanot (also with tailwind 2.0.2) I might have missed something f...
76
material ui Tooltip issue using Jest: TypeError document.createRange is not a function
@MorganDbs See jsdom/jsdom#317 We use the following patch for our tests: Does it fix your problem? U...
76
material ui [Tabs] Improve TabPanel demos, avoid validateDOMNesting warning
Note: the warning appears only because the demo code has: Changing it like this takes care of it: ...
72
material ui [Table] Fixing head in material
To be noted the header can be sticky positioned: https://codesandbox.io/s/k0vwm7xpl3 ...
67
material ui [TextField] Handle Chrome autofill
Also notice the yellow background for auto filled text can it be overridden? @garygrubb I did this v...
65
storybook Storybook build fails in Node 13 (cannot find module @babel/compat-data/corejs3-shipped-proposals)
Removing node_modules and yarn.lock and using node 13.13 has been helped for me. ...