簡體   English   中英

將 React 單元測試從 Enzyme 遷移到 React 測試庫

[英]Migrating React unit test from Enzyme to React Testing Library

我最近繼承了一個要求使用 RTL(目前使用 Enzyme)的代碼庫。 許多酶測試都非常簡單,並且沒有問題地通過:

const render = ({ firstName, surname } = {}) => {
  const props = { firstName, surname };
  return shallow(<MyComponent {...props} />);
};

test('renders firstName and surname', () => {
  expect(
    render({
      firstName: 'My first name',
      surname: 'My surname',
    })
  ).toMatchSnapshot();
});

我遇到了問題,但是將此測試遷移到 React 測試庫 - 我將以下內容作為一個非常粗略的起點,但知道它並不完全正確。 任何人都可以就此類基礎知識提出有用的文檔或建議任何代碼改進嗎? TIA

test('renders firstName and surname', () => {
  props = { firstName, surname };
  render(<MyComponent {...props} />);

  expect(screen.getByText(props.firstName)).toBe('My first name');
  expect(screen.getByText(props.surname)).toBe('My surname');
});

作為一個也必須與兩者一起工作的人,我了解到 RTL 在概念上與酶非常不同。 RTL 不鼓勵進行 prop 斷言,而是建議編寫用戶驅動的測試。 所以我的主要改進建議是在編寫測試之前思考並問自己“用戶現在看到了什么?” 或“用戶在屏幕上發生了什么變化?”。

在上面的測試中,您基本上是在檢查道具是否是您定義的道具,這就是酶的作用方式,但是當您停下來考慮它時,它是非常多余的。

我完全理解某些組件非常簡單並且沒有太多要測試的內容,因此在這種情況下,我會以以下方式重新編寫您的測試,以更符合 RTL 的精神,在這種情況下是沿着“用戶看到我期望他們看到的東西嗎?”的思路。 此外,我建議將您的元素查詢放入變量中以獲得更好的可讀性。

it('renders firstName and surname', () => {
  const props = {
    firstName: 'My first name',
    surname: 'My surname',
  };

  render(<MyComponent {...props} />);
  const firstName = screen.getByText(props.firstName);
  const surname = screen.getByText(props.surname);

  expect(firstName).toBeInTheDocument();
  expect(surname).toBeInTheDocument();
});

暫無
暫無

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

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