Why clear method not exist on @testing-library/user-event
Asked Answered
I

2

7

I am working on a CMS project and I just came across an issue. _userEvent.default.clear is not a function.

import user from '@testing-library/user-event'

test('can edit label', async () => {
    createArticleMock()
    await renderRootAndInitStore(rightNowTeasers, globalInitialState)

    const index = 1
    const input = screen.getByDisplayValue(labels[index])
    const newLabel = 'VÄRLDEN'
    user.clear(input)
    user.type(input, newLabel)

    expect(await screen.findByDisplayValue(newLabel))
    user.click(screen.getByTestId('settings-form-save'))
    await screen.findByText(newLabel)
})

When I visit @testing-library/user-event, I see those lines

// Definitions by: Wu Haotian <https://github.com/whtsky>
export interface IUserOptions {
    allAtOnce?: boolean;
    delay?: number;
}

export interface ITabUserOptions {
    shift?: boolean;
    focusTrap?: Document | Element;
}

export type TargetElement = Element | Window;

declare const userEvent: {
    click: (element: TargetElement) => void;
    dblClick: (element: TargetElement) => void;
    selectOptions: (element: TargetElement, values: string | string[]) => void;
    type: (
        element: TargetElement,
        text: string,
        userOpts?: IUserOptions
    ) => Promise<void>;
    tab: (userOpts?: ITabUserOptions) => void;
};

export default userEvent;

As the file shows, there is no clear() method on userEvent. But the documentation points out to clear() method.

Doc => Doc

This is first time I use this library. Anyone knows what the issue is?

Illconsidered answered 8/6, 2020 at 8:46 Comment(2)
It looks like those types are missing two of the documented methods - toggleSelectOptions isn't there either. They're both there in the latest version (github.com/testing-library/user-event/blob/master/typings/…), maybe you need to update or wait for a release.Topless
npm i -D @testing-library/user-event and npm audit fix solved the issue. Thanks jonrsharpeIllconsidered
E
5

You Have to update the @testing-library/user-event to the latest version. Then that error will be resolved. You Can find the latest version over here: https://www.npmjs.com/package/@testing-library/user-event

Eberhart answered 8/9, 2021 at 2:57 Comment(0)
G
0

As discussed in the other answers/comments, the best solution is to upgrade @testing-library/user-event. However, if you are stuck on an old version for some reason, you can use this workaround.

Instead of this:

user.clear(input);

try this:

user.type(input, "", { allAtOnce: true });
Gian answered 8/2, 2023 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.