选择带有测试库的下拉元素

Tre*_*ams 3 testing-library

显然我根本不理解测试库。它们具有“单击”功能,但似乎没有用于从选择元素中选择简单下拉选项的功能。这是失败的,表示选择了 0,而不是预期的 1。我如何使选择工作?


import React from "react";
import {render} from '@testing-library/react'
import {screen} from '@testing-library/dom'

let container: any;
beforeEach(() => {
    container = document.createElement('div');
    document.body.appendChild(container);
});

afterEach(() => {
    document.body.removeChild(container);
    container.remove();
    container = null;
});

it('AddRental should display', () => {
    render(<select name="town" data-testid="town" className="form-control"
                   aria-label="Select the Town">
        <option value="0">--Town--</option>
        <option value="1">My town</option>
        <option value="2">Your Town</option>
        <option value="3">The other town</option>
    </select>, {container});
    const dropdown = screen.getByTestId('town');
    expect(dropdown.value)
        .toBe('0');
    dropdown.click();
    const athabascaOption = screen.getByText('My town');
    athabascaOption.click();
    const byTestId = screen.getByTestId('town');
    expect(byTestId.value)
        .toBe('1')
});
Run Code Online (Sandbox Code Playgroud)

小智 7

您可以用于fireEvent此目的。它可以从以下位置导入@testing-library/react(screen顺便说一下,为了方便起见,也可以):

import {render, screen, fireEvent} from '@testing-library/react'
Run Code Online (Sandbox Code Playgroud)

这是使用此函数重写的测试用例:

render(
    <select
        name="town"
        data-testid="town"
        className="form-control"
        aria-label="Select the Town"
    >
        <option value="0">--Town--</option>
        <option value="1">My town</option>
        <option value="2">Your Town</option>
        <option value="3">The other town</option>
    </select>,
    { container },
);
const dropdown = screen.getByTestId('town') as HTMLSelectElement;
expect(dropdown.value).to.equal('0');
fireEvent.change(dropdown, { target: { value: '1' } });
expect(dropdown.value).to.equal('1');
Run Code Online (Sandbox Code Playgroud)

为了进一步解释,这个 GitHub 问题和这个 CodeSandbox 中的问题评论中有一些有用的讨论。