在Jest中模拟按钮单击

时间:2017-05-02 21:17:52

标签: javascript testing jestjs enzyme

模拟按钮单击似乎是一种非常简单/标准的操作。然而,我无法在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

6 个答案:

答案 0 :(得分:68)

#1使用Jest

这就是我使用jest模拟回调函数来测试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是一个测试实用程序,可以更容易地断言和选择您的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);
});

答案 1 :(得分:5)

使用jest你可以这样做:

test('should call 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();
});

答案 2 :(得分:0)

你可以使用类似这样的东西来调用点击时写的处理程序:

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

page = <MyCoolPage />;
pageMounted = shallow(page);
// below line will execute your click function
pageMounted.instance().yourOnClickFunction();

答案 3 :(得分:0)

除了在同级注释中建议的解决方案之外,您还可以稍微更改测试方法,并且一次不测试整个页面(使用深子级组件树),但要进行隔离的组件测试。这将简化onClick()和类似事件的测试(请参见下面的示例)。

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

下面是一个示例,说明如何使用Jestreact-test-renderer在孤立的onClick()组件中测试SearchForm事件。

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

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

应该在版本4中删除酶模拟。主要维护人员建议直接调用prop函数。一种解决方案是直接测试调用这些道具是否正确。或者您可以模拟出实例方法,测试prop函数调用它们,然后对实例方法进行单元测试。

您可以调用点击

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

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

有关弃用的信息: https://github.com/airbnb/enzyme/issues/2173

相关问题