在 Jest 中模拟按钮点击 [英] Simulate a button click in Jest
问题描述
模拟按钮点击似乎是一个非常简单/标准的操作.但是,我无法在 Jest.js 测试中使用它.
Simulating a button click seems like a very easy/standard operation. Yet, I can't get it to work in Jest.js tests.
这是我尝试过的(也使用 jQuery),但它似乎没有触发任何东西:
This is what I tried (and also doing it using jQuery), but it didn't seem to trigger anything:
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 Using Jest
这是我如何使用 Jest 模拟回调函数来测试点击事件:
This is how I use the Jest mock callback function to test the click event:
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 组件
I am also using a module called enzyme. Enzyme is a testing utility that makes it easier to assert and select your React Components
#2 使用诗乃
此外,您可以使用另一个名为 Sinon 的模块,它是一个独立的测试间谍、存根和模拟JavaScript.这是它的外观:
Also, you can use another module called Sinon which is a standalone test spy, stubs and mocks for JavaScript. This is how it looks:
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 使用自己的间谍
最后,您可以制作自己的天真的间谍(除非您有正当理由,否则我不推荐这种方法).
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);
});
这篇关于在 Jest 中模拟按钮点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!