Solvedant design Impossible to expand Select component dropdown programatically
✔️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.
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:
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.
This used to work in Ant design 3.x.x but seems to be broken now after updating to ant design 4.0.2.