在 Jest 中模拟按钮点击

Simulate a button click in Jest

模拟按钮点击似乎是一个非常easy/standard的操作。然而,我无法让它在 Jest.js 测试中工作。

这是我尝试过的方法(也是使用 jQuery 进行的),但它似乎没有触发任何东西:

import { mount } from 'enzyme';

page = <MyCoolPage />;
pageMounted = mount(page);

const button = pageMounted.find('#some_button');
expect(button.length).toBe(1); // It finds it alright
button.simulate('click'); // Nothing happens

#1 使用 Jest

我是这样使用 Jest mock 回调函数来测试点击事件的:

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

describe('Test Button component', () => {
  it('Test click event', () => {
    const mockCallBack = jest.fn();

    const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
    button.find('button').simulate('click');
    expect(mockCallBack.mock.calls.length).toEqual(1);
  });
});

我也在使用一个名为 enzyme 的模块。 Enzyme 是一种测试实用程序,可以更轻松地断言和 select 您的 React 组件

#2 使用 Sinon

此外,您可以使用另一个名为 Sinon 的模块,它是 JavaScript 的独立测试间谍、存根和模拟。这是它的样子:

import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';

import Button from './Button';

describe('Test Button component', () => {
  it('simulates click events', () => {
    const mockCallBack = sinon.spy();
    const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));

    button.find('button').simulate('click');
    expect(mockCallBack).toHaveProperty('callCount', 1);
  });
});

#3 使用你自己的间谍

最后,您可以制作自己的天真间谍(除非您有正当理由,否则我不推荐这种方法)。

function MySpy() {
  this.calls = 0;
}

MySpy.prototype.fn = function () {
  return () => this.calls++;
}

it('Test Button component', () => {
  const mySpy = new MySpy();
  const mockCallBack = mySpy.fn();

  const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));

  button.find('button').simulate('click');
  expect(mySpy.calls).toEqual(1);
});

您可以使用类似这样的方式来调用点击时编写的处理程序:

import { shallow } from 'enzyme'; // Mount is not required

page = <MyCoolPage />;
pageMounted = shallow(page);

// The below line will execute your click function
pageMounted.instance().yourOnClickFunction();

使用 Jest,您可以这样做:

test('it calls start logout on button click', () => {
    const mockLogout = jest.fn();
    const wrapper = shallow(<Component startLogout={mockLogout}/>);
    wrapper.find('button').at(0).simulate('click');
    expect(mockLogout).toHaveBeenCalled();
});

除了同级评论中建议的解决方案之外,您可以稍微更改一下测试方法,而不是一次测试整个页面(使用较深的子组件树),但进行 isolated 组件测试。这将简化 onClick() 和类似事件的测试(参见下面的示例)。

想法是一次只测试 一个 个组件,不是所有 个组件一起测试。在这种情况下,将使用 jest.mock() 函数模拟所有子组件。

这是一个示例,说明如何使用 Jest and react-test-renderer.

在孤立的 SearchForm 组件中测试 onClick() 事件
import React from 'react';
import renderer from 'react-test-renderer';
import { SearchForm } from '../SearchForm';

describe('SearchForm', () => {
  it('should fire onSubmit form callback', () => {
    // Mock search form parameters.
    const searchQuery = 'kittens';
    const onSubmit = jest.fn();

    // Create test component instance.
    const testComponentInstance = renderer.create((
      <SearchForm query={searchQuery} onSearchSubmit={onSubmit} />
    )).root;

    // Try to find submit button inside the form.
    const submitButtonInstance = testComponentInstance.findByProps({
      type: 'submit',
    });
    expect(submitButtonInstance).toBeDefined();

    // Since we're not going to test the button component itself
    // we may just simulate its onClick event manually.
    const eventMock = { preventDefault: jest.fn() };
    submitButtonInstance.props.onClick(eventMock);

    expect(onSubmit).toHaveBeenCalledTimes(1);
    expect(onSubmit).toHaveBeenCalledWith(searchQuery);
  });
});

我需要自己对按钮组件进行一些测试。这些测试对我有用 ;-)

import { shallow } from "enzyme";
import * as React from "react";
import Button from "../button.component";

describe("Button Component Tests", () => {
    it("Renders correctly in DOM", () => {
        shallow(
            <Button text="Test" />
        );
    });
    it("Expects to find button HTML element in the DOM", () => {
        const wrapper = shallow(<Button text="test"/>)
        expect(wrapper.find('button')).toHaveLength(1);
    });

    it("Expects to find button HTML element with className test in the DOM", () => {
        const wrapper = shallow(<Button className="test" text="test"/>)
        expect(wrapper.find('button.test')).toHaveLength(1);
    });

    it("Expects to run onClick function when button is pressed in the DOM", () => {
        const mockCallBackClick = jest.fn();
        const wrapper = shallow(<Button onClick={mockCallBackClick} className="test" text="test"/>);
        wrapper.find('button').simulate('click');
        expect(mockCallBackClick.mock.calls.length).toEqual(1);
    });
});

已接受答案中的解决方案已被弃用

#4 直接调用prop

Enzyme simulate 应该在版本 4 中被删除。主要维护者建议直接调用 prop 函数,这是 simulate 在内部所做的。一种解决方案是直接测试调用这些道具是否正确;或者您可以模拟实例方法,测试 prop 函数调用它们,并对实例方法进行单元测试。

你可以调用click,例如:

wrapper.find('Button').prop('onClick')() 

或者

wrapper.find('Button').props().onClick() 

关于弃用的信息: Deprecation of .simulate() #2173

测试库通过 click function.

让您轻松完成这项工作

它是 user-event 库的一部分,可用于每个 dom 环境(反应、jsdom、浏览器等)

文档中的示例:

import React from 'react'
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'

test('click', () => {
  render(
    <div>
      <label htmlFor="checkbox">Check</label>
      <input id="checkbox" type="checkbox" />
    </div>,
  )

  userEvent.click(screen.getByText('Check'))
  expect(screen.getByLabelText('Check')).toBeChecked()
})