如何监视 React 功能组件内的方法?

Pab*_*rde 5 reactjs jestjs react-testing-library

我有这个功能组件。

搜索.js


function Search() {
  const [term, setTerm] = useState('sun');

  function handleOnChange(e) {
    if (!e.target.value) {
      return false;
    }
    setTerm(e.target.value);
    return true;
  }

  return <input type="text" onChange={handleOnChange} placeholder="Search" />
}

Run Code Online (Sandbox Code Playgroud)

搜索.test.js

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

describe('when type a valid term', () => {
  it('update the state', () => {
    const { getByPlaceholderText } = render(<Search />;

    // this doesn't work. The handleOnChange method is private. How to deal with this?
    const handlerSpy = jest.spyOn(Search, 'handleOnChange');

    fireEvent.click(getByPlaceholderText(/search/i), { target: { value: 'moon' } });

    expect(handlerSpy).toHaveReturnedWith(true);
  });
});


Run Code Online (Sandbox Code Playgroud)

我不知道我是否尝试了错误的方法。我只需要测试如果用户输入空术语会发生什么。感谢任何建议。

Pab*_*rde 1

如果您有更好的答案,请留在这里。在搜索了不同的方法之后,我意识到了另一种测试方法。

首先,我将当前状态附加到搜索字段的值属性中。

这样,我可以检查我的搜索字段的属性值是否相应变化


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

describe('when type a valid term', () => {
  it('update the state', () => {
    const { getByPlaceholderText } = render(<Search />);
    const inputField = getByPlaceholderText(/search/i);
    fireEvent.change(inputField, { target: { value: 'moon' } });

    expect(inputField).toHaveValue('moon');
  });
});

Run Code Online (Sandbox Code Playgroud)

也可以编写快照测试。