簡體   English   中英

如何測試一個組件在 React 中渲染了多少次?

[英]How to test how many times a component was rendered in React?

我有一個包含 2 個組件的場景:

  • 應用程序
  • 人們

我想測試 People 在 App 中是否被渲染了 10 次。 所以,我正在嘗試使用 Jest 來測試它。 到目前為止,我在我的src/App.test.js上做了這個:

import React, { Component } from "react";
import People from "./components/People";
import App from './App';

test('Total people = 10', () => {
    expect(App).find(People).toHaveLength(10);
});

但是我收到一條消息說:

類型錯誤:expect(...).find 不是函數。

如何使用 React 和 Jest 測試一個組件在另一個組件中渲染的次數? 誰能幫我?

為了首先測試 react 組件,你需要渲染它們,有一些工具可以做到這一點,但是由於你在這個測試中的推理是檢查一個組件在另一個組件中渲染了多少次,的淺層方法做得很好.

import React from "react";
import App from "./App";
import People from "./components/People";
import { shallow } from "enzyme";

it("Total people = 10", () => {
  const wrapper = shallow(<App />);
  expect(wrapper.find(People)).toHaveLength(10);
});

您需要先在您的項目中設置酶,閱讀文檔以獲取更多詳細信息。

目前測試的趨勢是檢查用戶在頁面中實際看到的內容,所以大多數人都在使用react-testing-library ,檢查一下對你有好處

如果您切換到react-testing-library ,您可能會編寫如下測試:

import React, { Component } from "react";
import App from './App';
import {render} from "@testing-library/react";


test('Total people = 10', async () => {
    const { getAllByText } = await render(<App />);

    expect(getAllByText('string_in_People')).toHaveLength(10);
});

基本上,您將使用庫的內置getAllBy...查詢方法之一來查詢在<People />組件的每個實例中只出現一次的元素的所有實例。 結果集的長度將等於頁面上<People />實例的數量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM