1

显然我根本不了解测试库。它们具有“单击”功能,但似乎没有从选择元素中选择简单下拉选项的功能。这是失败的,说选择了 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')
});
4

1 回答 1

1

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

import {render, screen, fireEvent} from '@testing-library/react'

这是重写以使用此功能的测试用例:

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');

为了进一步解释,在这个 GitHub 问题这个 CodeSandbox中有一些有用的讨论,来自对该问题的评论。

于 2020-11-13T15:53:16.077 回答