React is a popular library for creating web apps and mobile apps.
In this article, we’ll look at some tips for writing better React apps.
To simulate a button click with Jest, we can write:
import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';
describe('Test button', () => {
it('Test click event', () => {
const mockOnClick = jest.fn();
const button = shallow((<Button onClick={mockOnClick}>click me</Button>));
button.find('button').simulate('click');
expect(mockOnClick.mock.calls.length).toEqual(1);
});
});
We create a mock function with and pass it into our button component.
Then we get the button and call simulate
with the argument 'click'
do simulate a click.
Then we can check if the mockOnClick
function is called at the end.
Alternatively, we can write similar code in a Sinon test.
For instance, we can write:
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 mockOnClick = sinon.spy();
const button = shallow((<Button onClick={mockOnClick}>click me</Button>));
button.find('button').simulate('click');
expect(mockOnClick).toHaveProperty('callCount', 1);
});
});
#programming #technology #javascript #web-development #software-development