如何为“@testing-library/react”fireEvent "clear mocks"?

How to "clear mocks" for the "@testing-library/react" fireEvent?

我正在使用 @testing-library/react 测试带有遗留代码的应用程序。基本上,每次我单击一个按钮时都会显示一个消息组件。该消息是遗留代码。此遗留组件在 DOM.

中注入 HTML

当测试我的应用程序时,我意识到遗留代码注入的代码在测试之间并不清晰。

Repos.js

import React, { useState } from 'react';

function showMessage() {
  const message = document.createElement('div');
  message.innerHTML = '<h1>Successfully saved!</h1>';
  document.body.appendChild(message);
}

export default function Repo() {
  const [repos, setRepos] = useState([]);

  function handleOnClick() {
    setRepos([
      { name: 'Repo 1' },
      { name: 'Repo 2' },
    ]);
    showMessage();
  }

  return (
    <nav>
      <button onClick={handleOnClick}>Show repos</button>
      <ul>
        {repos.map(repo => <li data-testid={repo.name} key={repo.name}>{repo.name}</li>)}
      </ul>
    </nav>
  )
}

Repos.test.js

import React from 'react';
import Repos from './Repos';
import { render, cleanup, fireEvent } from '@testing-library/react';


describe('Repos', () => {
  describe('when clicking the button', () => {
    beforeEach(() => cleanup());

    it('should updates repos collection', () => {
      const { container, getByText, getByTestId } = render(<Repos />)

      fireEvent.click(getByText('Show repos'));

      expect(getByTestId('Repo 1')).toBeTruthy();
      console.log(container.innerHTML);
    });

    it('should show the success message component', () => {
      const { container, getByText } = render(<Repos />)

      fireEvent.click(getByText('Show repos'));


      expect(getByText('Successfully saved!')).toBeTruthy();
      console.log(container.innerHTML);
    })
  })
})

您可能(并且需要)在每次测试前清洁 document

beforeEach(() => {
  document.body.innerHTML = "";
});

如果碰巧你的 showMessage 在单独的文件中,我建议你在测试中模拟它。这样你也可以避免在任何地方测试它的内部结构(当然除了针对 showMessage 本身的测试)