在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使用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是一个测试实用程序,可以更容易断言和选择你的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
此外,您还可以使用另一个名为 sinon 这是一个独立的测试间谍,存根和JavaScript的JavaScript。这是它的样子
Also you can use another module called sinon which is a standalone test spies, stubs and mocks for JavaScript. This is how does it look
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
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屋!