如何为“ @ testing-library / react” fireEvent“清除模拟”?

时间:2019-10-19 19:44:58

标签: reactjs jestjs react-testing-library

我正在使用@testing-library/react用遗留代码测试应用程序。基本上,每次我单击一个按钮都会显示一个消息组件。该消息是旧代码。这个旧组件将HTML注入DOM。

在对我的应用程序进行测试时,我意识到在两次测试之间,旧代码注入的代码并不清晰。

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

enter image description here

1 个答案:

答案 0 :(得分:0)

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

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

如果您的showMessage处于单独的文件中,建议您在测试中对其进行模拟。这样,您还可以避免在任何地方都对其内部进行测试(肯定要侧重于showMessage本身的测试除外)