Javascript 在 Jest 中模拟一个按钮点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43747397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simulate a button click in Jest
提问by foobar
Simulating a button click seems like a very easy/standard operation. Yet, I can't get it to work in Jest.js tests.
模拟按钮点击似乎是一个非常简单/标准的操作。然而,我无法让它在 Jest.js 测试中工作。
This is what I tried (and also doing it using jquery), but it didn't seem to trigger anything:
这是我尝试过的(也使用 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
回答by Saman Shafigh
#1 Using Jest
#1 使用 Jest
This is how I use the jest mock callback function to test the click event
这就是我如何使用 jest 模拟回调函数来测试点击事件
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);
});
});
I am also using a module called enzymeEnzyme is a testing utility that makes it easier to assert and select your React Components
我还使用了一个名为酶的模块 Enzyme 是一个测试实用程序,可以更轻松地断言和选择您的 React 组件
#2 Using Sinon
#2 使用诗乃
Also, you can use another module called sinonwhich is a standalone test spy, stubs and mocks for JavaScript. This is how does it look
此外,您可以使用另一个名为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 Using Your own Spy
#3 使用你自己的间谍
Finally, you can make your own naive spy (I don't recommend this approach unless you have a valid reason for that.)
最后,您可以制作自己的天真的间谍(除非您有正当理由,否则我不推荐这种方法。)
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);
});
回答by Black
Previous answers are being deprecated
以前的答案已被弃用
Enzyme simulate is supposed to be removed in version 4. Main maintainer is suggesting directly invoking prop functions, which is what simulate does internally. One solution is to directly test that invoking those props does the right thing; or you can mock out instance methods, test that the prop functions call them, and unit test the instance methods.
酶模拟应该在版本 4 中被删除。主要维护者建议直接调用 prop 函数,这就是模拟在内部所做的。一种解决方案是直接测试调用这些 props 是否正确;或者您可以模拟实例方法,测试 prop 函数是否调用它们,并对实例方法进行单元测试。
You could call click for example
例如,您可以调用 click
wrapper.find('Button').prop('onClick')()
or
或者
wrapper.find('Button').props().onClick()
Information about deprecation: https://github.com/airbnb/enzyme/issues/2173
回答by Hymangisel
Using jest you can do it like this:
使用 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();
});
回答by Oleksii Trekhleb
Additionally to the solutions that were suggested in sibling comments you may change your testing approacha little bit and test not the whole page all at once (with deep children components tree) but do an isolatedcomponent testing. This will simplify testing of onClick()and similar events (see example below).
除了在兄弟评论中建议的解决方案之外,您可以稍微改变您的测试方法,而不是一次测试整个页面(具有深子组件树),而是进行独立的组件测试。这将简化对onClick()类似事件的测试(参见下面的示例)。
The idea is to test only onecomponent at a time and not allof them together. In this case all children components will be mocked using jest.mock()function.
这个想法是一次只测试一个组件,而不是一起测试所有组件。在这种情况下,所有子组件都将使用jest.mock()函数进行模拟。
Here is an example of how onClick()event may be tested in isolated SearchFormcomponent using Jestand react-test-renderer.
这是一个如何使用Jest和react-test-rendereronClick()在隔离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);
});
});
回答by Hannibal B. Moulvad
I needed to do a little bit of testing myself of a button component. These tests works for me ;-)
我需要对按钮组件进行一些测试。这些测试对我有用;-)
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);
});
});
回答by utkarsh
You may use something like this to call the handler written on click:
你可以使用这样的东西来调用点击时编写的处理程序:
import { shallow } from 'enzyme'; // mount is not required
page = <MyCoolPage />;
pageMounted = shallow(page);
// below line will execute your click function
pageMounted.instance().yourOnClickFunction();

