在Jest中模拟按钮单击

fykwrbwg  于 2023-05-11  发布在  Jest
关注(0)|答案(9)|浏览(178)

模拟按钮点击似乎是一个非常简单/标准的操作。然而,我不能让它在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
ilmyapht

ilmyapht1#

#1使用Jest

下面是我如何使用Jest mock回调函数来测试click事件:

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是一个测试工具,可以更容易地Assert和选择React组件

#2使用兴农

此外,您可以使用另一个名为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);
});
jw5wzhpr

jw5wzhpr2#

已接受答案中的解决方案已弃用
**#4直接调用 prop **

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

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

或者

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

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

bsxbgnwa

bsxbgnwa3#

使用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();
});
hivapdat

hivapdat4#

Testing-library通过单击功能使您轻松完成此操作。
它是user-event库的一部分,可以用于每个dom环境(react、jsdom、browser……)
doc中的例子:

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()
})
0dxa2lsx

0dxa2lsx5#

你可以使用类似下面的代码来调用在点击时编写的处理程序:

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

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

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

vsmadaxz6#

除了兄弟评论中建议的解决方案之外,你可以稍微改变一下你的测试方法,不要一次测试整个页面(使用深层子组件树),而是做一个独立的组件测试。这将简化onClick()和类似事件的测试(参见下面的示例)。
这个想法是一次只测试一个组件,而不是一起测试所有**组件。在这种情况下,所有子组件都将使用jest.mock()函数进行模拟。
下面的示例说明了如何使用Jestreact-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);
  });
});
voase2hg

voase2hg7#

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

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

x6yk4ghg8#

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

describe("Test Button component", () => {
  let container = null;
  let clickFn = null;

  beforeEach(() => {
    clickFn = jest.fn();
    container = shallow(<Button buttonAction={clickFn} label="send" />);
  });
  it("button Clicked", () => {
    container.find("button").simulate("click");
    expect(clickFn).toHaveBeenCalled();
  });
});
zbq4xfa0

zbq4xfa09#

我总是用fireEvent测试按钮:

import { fireEvent } from "@testing-library/react";

it("Button onClick", async () => {
    const handleOnClick = jest.fn();

    const { getByTestId } = render(<Button onClick={handleOnClick} />);
    const element = getByTestId("button");

    fireEvent.click(element);

    expect(handleOnClick).toBeCalled();
    expect(element).toHaveClass("animate-wiggle");
});

相关问题