【问题标题】:React testing for the TextField element from Material UI从 Material UI 对 TextField 元素进行 React 测试
【发布时间】:2021-07-22 19:04:45
【问题描述】:

我正在尝试对 Textfield 元素进行 npm 测试,这就是我的 Textfield 元素的样子:

                        <TextField
                            inputProps ={{"data-testid": "testId"}}
                            title='titleInput'
                            label="Textbook Title*"
                            variant="filled"
                            fullWidth
                            style={{ marginTop: "20px" }}
                            value={this.state.title}
                            onChange={this.handleTitleChange}
                            autoFocus
                        />

这就是我的测试的样子:

export const selectMaterialUiSelectOption = async (element, optionText) =>
    new Promise(resolve => {
      // The the button that opens the dropdown, which is a sibling of the input
      const selectButton = element.parentNode.querySelector('[role=button]');

      // Open the select dropdown
      UserEvent.click(selectButton);

      // Get the dropdown element. We don't use getByRole() because it includes <select>s too.
      const listbox = document.body.querySelector('ul[role=listbox]');

      // Click the list item
      const listItem = within(listbox).getByText(optionText);
      UserEvent.click(listItem);

      // Wait for the listbox to be removed, so it isn't visible in subsequent calls
      waitForElementToBeRemoved(() => document.body.querySelector('ul[role=listbox]')).then(
          resolve,
      );
    });

describe("Render Testing of EditListing Page", () =>{
  test("Basic Render Test of EditListing Page", () => {
    render(<EditListing />);
  });
  test("Render Listing Text", () =>{
    selectMaterialUiSelectOption(getByTestId('testId'))
      }
  )

但是,它给了我这个错误:

  ● Render Testing of EditListing Page › Render Listing Text

    TypeError: Expected container to be an Element, a Document or a DocumentFragment but got string.

      481 |   });
      482 |   test("Render Listing Text", () =>{
    > 483 |     selectMaterialUiSelectOption(getByTestId('testId'), "10")
          |                                  ^
      484 |       }
      485 |   )
      486 |


关于如何解决此问题的任何想法?谢谢!

【问题讨论】:

    标签: reactjs jestjs material-ui


    【解决方案1】:

    您还必须在第二次测试中渲染您的组件,并且您可以从返回的对象中获取 getByTestId

    describe("Render Testing of EditListing Page", () => {
      test("Basic Render Test of EditListing Page", () => {
        render(<EditListing />);
      });
      test("Render Listing Text", async () => {
        const { getByTestId } = render(<EditListing />);
        await selectMaterialUiSelectOption(getByTestId("testId"));
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 2016-03-22
      • 1970-01-01
      • 2021-02-11
      • 2020-06-09
      • 2017-03-01
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      相关资源
      最近更新 更多