首页 > 解决方案 > 如何测试在 React、Jest、Enzyme 中作为 props 传递的函数

问题描述

我正在尝试使用作为道具传递给子组件的参数来测试一个函数。我想在它上面模拟一个“点击”事件。我不确定我是否以正确的方式做这件事。PS我没有收到任何错误。这是我下面的组件。

function MovieSummary({movie,addItem}) {
  return (
    <div key={movie.imdbID} className="movie-container">
     
      <div className="button-container">
        <button
          id="btn-click"
          key={movie.imdbID}
          disabled={disabled.indexOf(movie.imdbID) !== -1 || disableButton}
          className="btn btn-primary mt-3"
          onClick={() => {
            addItem({
              title: movie.Title,
              id: movie.imdbID,
              year: movie.Year,
            });
            handleDisabled(movie.imdbID);
          }}
        >
          Nominate
        </button>
      </div>
    </div>
  );
}

export default MovieSummary;

这是我下面的测试组件

 it("simulate add movies onclick", () => {
    const movie = {
      imdbID: 2,
      Title: "bola",
      Year: 1992,
      Poster: "https://media1.giphy.com/media/rwzBCbqt1jqMw/1",
    };

    const disabled = [2];

    const mockFn = jest.fn();

    const wrapper = shallow(
      <MovieSummary
        movie={movie}
        disabled={disabled}
        addItem={mockFn}
        handleDisabled={() => {}}
      />
    );

    wrapper.find("[id='btn-click']").simulate("click");

    expect(mockFn).toHaveBeenCalled();
  });

标签: reactjsjestjsenzyme

解决方案


是的,你做得对。这是一个完整的单元测试解决方案:

index.jsx

import React from 'react';

function MovieSummary({ movie, disabled, addItem, handleDisabled }) {
  const disableButton = false;
  return (
    <div key={movie.imdbID} className="movie-container">
      <div className="button-container">
        <button
          id="btn-click"
          key={movie.imdbID}
          disabled={disabled.indexOf(movie.imdbID) !== -1 || disableButton}
          className="btn btn-primary mt-3"
          onClick={() => {
            addItem({
              title: movie.Title,
              id: movie.imdbID,
              year: movie.Year,
            });
            handleDisabled(movie.imdbID);
          }}
        >
          Nominate
        </button>
      </div>
    </div>
  );
}

export default MovieSummary;

index.test.jsx

import { shallow } from 'enzyme';
import React from 'react';
import MovieSummary from './';

describe('64026812', () => {
  it('simulate add movies onclick', () => {
    const movie = {
      imdbID: 2,
      Title: 'bola',
      Year: 1992,
      Poster: 'https://media1.giphy.com/media/rwzBCbqt1jqMw/1',
    };
    const disabled = [2];
    const mAddItem = jest.fn();
    const mHandleDisabled = jest.fn();
    const wrapper = shallow(<MovieSummary movie={movie} disabled={disabled} addItem={mAddItem} handleDisabled={mHandleDisabled} />);
    const btn = wrapper.find('#btn-click');
    btn.simulate('click');
    expect(btn.prop('disabled')).toBeTruthy();
    expect(mAddItem).toBeCalledWith({ title: 'bola', id: 2, year: 1992 });
    expect(mHandleDisabled).toBeCalledWith(2);
  });
});

带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/64026812/index.test.tsx (10.143s)
  64026812
    ✓ simulate add movies onclick (14ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |       50 |      100 |      100 |                   |
 index.tsx |      100 |       50 |      100 |      100 |                11 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.494s, estimated 12s

推荐阅读