Test input element click invocation when label is clicked - reactjs

I want to test a scenario where an input component (radio/ checkbox) click event is invoked when the label is clicked. Following is my code,
Toggle.jsx
import * as React from 'react'; // eslint-disable-line import/no-extraneous-dependencies
import styled from 'styled-components'; // eslint-disable-line import/no-extraneous-dependencies
import Label from '../Label/Label';
const ToggleButtonController = styled.button`
background-color: red;
`;
const ToggleInputController = styled.input`
background-color: red;
`;
const Toggle = (props) => {
const { label } = props;
let toggleControllerRef = null;
const renderLabel = () => {
return (
<Label
onClick={() => { toggleControllerRef.click(); }} // <--- untested line where I invoke the input element click event on label click
>
{ label }
</Label>
);
};
const renderController = () => {
const { labelPosition, disabled, type, onClick, onChange } = props;
let controller = (
<div>
<ToggleInputController
onClick={onClick}
onChange={onChange}
innerRef={(toggleController) => { toggleControllerRef = toggleController; }}
type={type === 'switch' ? 'checkbox' : type}
disabled={disabled}
/>
</div>
);
if (type === 'button') {
controller = (
<div>
<ToggleButtonController
onClick={onClick}
disabled={disabled}
{...commonUtils.filterProps(Toggle.propTypes, props)}
>
{ label }
</ToggleButtonController>{ renderRequired() }
</div>
);
}
return controller;
};
return (
<div>
{
renderController()
}
</div>
);
};
export default Toggle;
toggle.test.js
import React from 'react';
import { shallow } from 'enzyme';
import { Toggle } from '../src/index';
describe('Test Toggle component', () => {
it('Test checkbox element label click event', () => {
const mockCallBack = jest.fn();
const toggle = shallow(<Toggle type="checkbox" onClick={mockCallBack} label="test" />);
toggle.find('Label').last().get(0).click; // i want to trigger onClick in the above Toggle when the label is clicked
expect(mockCallBack).toHaveBeenCalled();
});
});
With this code snippet, the test fails stating the mockCallBack was not called.
This is the first time im testing UI elements and would appreciate a point in the right direction to achieve this requirement.
Thanks

There are a couple of details you should consider to write this test.
Simulating events
In order to simulate events, Enzyme wrappers provide the .simulate method:
wrapper.find('a').simulate('click');
Simulating events with shallow rendering
Simulated events with shallow rendering, don't propagate as expected. Therefore there are at least 2 options:
Keep using shallow render and call .simulate directly on the element bound to the event callback
Switch to Enzyme's full rendering to take advantage on proper events propagation

Related

Testing a CallBack function in a function which get triggered forButton Onclick using jest

I have a React child component which has button
export function Banner({argumentSetter}){
function handleOnClick(){
argumentSetter(argument.READ);
}
return(
<div>
<Button onClick={handleOnClick}>
<Icon name="delete" type="filled">
Discard
</Icon>
</Button>
</div>
)
}
And I have my argumentSetter in my parent component defined as following,
const [argument,setArgument] = useState<Argument>(argument.EDIT);
argumentSetter = useCallBack((val)=>{
setArgument(val);
},[argument]);
return(
<div>
<Banner argumentSetter={argumentSetter}/>
</div>
)
How to get 100% test coverage using jest.
To test the banner, your code should be like the following
import React from "react";
import { mount } from "enzyme";
import { Banner } from "./Banner.js";
import { argument } from "./arguments.js";
it("Button click leads to argument.READ", async () => {
let promiseResolve = null;
const argPromise = new Promise((resolve) => {
promiseResolve = resolve;
});
const argumentSetter = (arg) => promiseResolve(arg);
const banner = mount(<Banner argumentSetter={argumentSetter} />);
banner.find("button").simulate("click");
const newArg = await argPromise;
expect(newArg).toEqual(argument.READ);
});
Explanation:
We create an externally fulfillable promise variable, called argPromise which will resolve when promiseResolve is called, which is called when the argumentSetter is called. Hence, when the button click is simulated, it will resolve the updated argument to newArg variable (which should be argument.READ), and hence you can test if it matches your expectation.
This should hence cover all lines of your Banner component during testing.

How can I test a click event which changes a useState state with enzyme?

I have the following component:
import React, { useState } from "react";
import { Button, ThirteenBold } from "#selfdecode/sd-component-library";
import { PlayIcon } from "assets/icons";
import { TourButtonProps } from "./interfaces";
import { WelcomeVideoModal } from "../../modals/welcome-video-modal";
/**
* The tour button.
*/
export const TourButton: React.FC<TourButtonProps> = (props) => {
const [isIntroVideoShowing, setIsIntroVideoShowing] = useState(false);
return (
<>
<WelcomeVideoModal
isOpen={isIntroVideoShowing}
onClickX={() => setIsIntroVideoShowing(false)}
data-test="tour-button-welcome-video"
/>
<Button
{...props}
width={["max-content"]}
variant="tour"
onClick={() => setIsIntroVideoShowing(true)}
data-test="tour-button"
>
<ThirteenBold
mr={["12px"]}
color="cl_blue"
width={["max-content"]}
letterSpacing={["1px"]}
display={["none", "block"]}
textTransform="uppercase"
>
welcome tour
</ThirteenBold>
<PlayIcon style={{ height: "30px", fill: "#4568F9" }} />
</Button>
</>
);
};
And the test coverage report is complaining that I am not testing both of the onClick events, which change the state.
I've tried two approaches, and both fail.
Approach one was to mock the useState and see if it gets called as I'd have expected it.
This was the test I tried:
const setState = jest.fn();
const useStateMock: any = (initState: any) => [initState, setState];
jest.spyOn(React, "useState").mockImplementation(useStateMock);
const button = wrapper.find(`[data-test="tour-button"]`);
expect(button).toHaveLength(1);
button.simulate("click");
expect(setState).toHaveBeenCalled();
This shouldn't even be the final test, as it doesn't check what was the valuee it was called with, but still, it failed because useState wasn't even called.
The second approach I've tried was to check the prop value on this component:
<WelcomeVideoModal
isOpen={isIntroVideoShowing}
onClickX={() => setIsIntroVideoShowing(false)}
data-test="tour-button-welcome-video"
/>
And this is the test I've tried
test("Check the isIntroVideoShowing changes to true on buton click", () => {
jest.spyOn(React, "useState").mockImplementation(useStateMock);
const button = wrapper.find(`[data-test="tour-button"]`);
const welcomeVideo = wrapper.find(
`[data-test="tour-button-welcome-video"]`
);
expect(button).toHaveLength(1);
expect(welcomeVideo.prop("isOpen")).toEqual(false);
button.simulate("click");
expect(welcomeVideo.prop("isOpen")).toEqual(true);
});
This one failed claiming it was called with false even after the click.
Is there a way to make these work? Or a different approach to cover these?
You need to give wrapper.update for updating the template with state changes after simulating the click event.
test("Check the isIntroVideoShowing changes to true on buton click", () => {
jest.spyOn(React, "useState").mockImplementation(useStateMock);
const button = wrapper.find(`[data-test="tour-button"]`);
const welcomeVideo = wrapper.find(
`[data-test="tour-button-welcome-video"]`
);
expect(button).toHaveLength(1);
expect(welcomeVideo.prop("isOpen")).toEqual(false);
button.simulate("click");
wrapper.update();
expect(welcomeVideo.prop("isOpen")).toEqual(true);
});
Reference - https://enzymejs.github.io/enzyme/docs/api/ShallowWrapper/update.html

Testing mouse event listener added using ref in React functional component

Hi I have a functional component as shown below:
import React, { useRef, useEffect, useState } from 'react';
const SomeComponent = ({ prop1, ...otherProps}) => {
const divRef = useRef();
useEffect(() => {
divRef.current.addEventListener('mousedown', mouseDownFunc);
}, []);
const mouseDownFunc = () => {
document.addEventListener('mousemove', (el) => {
// call some parent function
});
}
return (
<div
className='test-div'
ref={ divRef }>
</div>
);
};
How do I test a react functional component wherein addEventListener is added using ref inside useEffect which when triggered calls mouseDownFunc.
I'm new to react jest testing, little confused on how to do it.
Testing this sort of component can be tricky, but using #testing-library/react I think I was able to come up with something useful.
I did have to make some changes to your component to expose the API a bit, and I also made some changes so that it stops listening to the events on mouseup which may not be the specific event you want.
Here's the modified component:
// MouseDownExample.js
import React, { useEffect, useState } from "react";
export default ({ onMouseMoveWhileDown }) => {
const [x, setX] = useState(null);
const [listening, setListening] = useState();
// Replaced with mouse move function, should make sure we're unlistening as well
useEffect(() => {
if (listening) {
const onMouseMove = (event) => {
// call some parent function
onMouseMoveWhileDown(event);
console.log(event.clientX);
// purely for testing purposes
setX(event.clientX);
};
const onMouseUp = (event) => {
// stop listening on mouse up
// - you should pick whatever event you want to stop listening
// - this is global so it also stops when the mouse is outside the box
setListening(false);
};
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
return () => {
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
};
}
}, [listening, onMouseMoveWhileDown]);
return (
<div
style={{
backgroundColor: "red",
width: 200,
height: 200
}}
className="test-div"
onMouseDown={() => {
// moved this inline, so no ref
setListening(true);
}}
>
X Position: {x}
</div>
);
};
I called out in comments the main differences.
And here's an example test:
// MouseDownExample.test.js
import React from "react";
import { fireEvent, render } from "#testing-library/react";
import MouseDownExample from "./MouseDownExample";
it("shouldn't trigger onMouseMoveWhileDown when mouse isn't down", () => {
const onMouseMoveWhileDown = jest.fn();
const { container } = render(
<MouseDownExample onMouseMoveWhileDown={onMouseMoveWhileDown} />
);
// Note: normally I would use `screen.getByRole` but divs don't have a useful role
const subject = container.firstChild;
fireEvent.mouseMove(
document,
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent
{
clientX: 200
}
);
// hasn't gone down yet
expect(onMouseMoveWhileDown).not.toHaveBeenCalled();
fireEvent.mouseDown(subject);
fireEvent.mouseUp(subject);
// went down then up before moving
fireEvent.mouseMove(document, {
clientX: 200
});
expect(onMouseMoveWhileDown).not.toHaveBeenCalled();
});
it("should trigger onMouseMoveWhileDown when mouse is down", () => {
const onMouseMoveWhileDown = jest.fn();
const { container } = render(
<MouseDownExample onMouseMoveWhileDown={onMouseMoveWhileDown} />
);
// Note: normally I would use `screen.getByRole` but divs don't have a useful role
const subject = container.firstChild;
fireEvent.mouseDown(subject);
fireEvent.mouseMove(document, {
clientX: 200
});
expect(onMouseMoveWhileDown).toHaveBeenCalledWith(
expect.objectContaining({ clientX: 200 })
);
});
What's happening here, is we're rendering the component, then firing events to ensure the onMouseMoveWhileDown function prop is called when we expect.
We have to do expect.objectContaining rather than just the object because it's called with a MouseEvent which contains other properties.
Another test we might want to add is an unmount test to ensure the listeners are no longer triggering events.
You can look at/experiment with this Code Sandbox with this component and the tests. Hope this helps 👍

react functional component with ag grid cannot call parent function via context

I am using ag-grid-react and ag-grid-community version 22.1.1. My app is written using functional components and hooks. I have a cellrenderer component that is attempting to call a handler within the parent component using the example found here. Is this a bug in ag-grid? I have been working on this application for over a year as I learn React, and this is my last major blocker so any help or a place to go to get that help would be greatly appreciated.
Cell Renderer Component
import React from 'react';
import Button from '../../button/button';
const RowButtonRenderer = props => {
const editClickHandler = (props) => {
let d = props.data;
console.log(d);
props.context.foo({d});
//props.editClicked(props);
}
const deleteClickHandler = (props) => {
props.deleteClicked(props);
}
return (<span>
<Button classname={'rowbuttons'} onClick={() => { editClickHandler(props) }} caption={'Edit'} />
<Button classname={'rowbuttons'} onClick={() => { deleteClickHandler(props) }} caption={'Delete'} />
</span>);
};
export default RowButtonRenderer;
Parent Component
function Checking() {
function foo(props) {
let toggle = displayModal
setNewData(props);
setModalDisplay(!toggle);
}
const context = {componentParent: (props) => foo(props)};
const gridOptions = (params) => {
if (params.node.rowIndex % 2 === 0) {
return { background: "#ACC0C6" };
}
};
const frameworkComponents = {
rowButtonRenderer: RowButtonRenderer,
};
.
.
.
return (
<>
<AgGridReact
getRowStyle={gridOptions}
frameworkComponents={frameworkComponents}
context = {context}
columnDefs={columnDefinitions}
rowData={rowData}
headerHeight="50"
rowClass="gridFont"
></AgGridReact>
</>
);
}
When clicking the edit button on a row, the debugger says that there is a function.
This error is received though:
You are passing the context object in this code section:
const context = {componentParent: (props) => foo(props)};
...
<AgGridReact
context={context}
{...}
></AgGridReact>
And in your cell renderer you call this
props.context.foo({d});
While it should be this
props.context.componentParent({d});
Also you can assign your callback directly since it receives the same parameter and returns the same result (if any)
function foo(props) {
let toggle = displayModal
setNewData(props);
setModalDisplay(!toggle);
}
const context = {componentParent: foo};
You can also use this shorthand syntax from ES6 when assigning object property
function componentParent(props) {
let toggle = displayModal
setNewData(props);
setModalDisplay(!toggle);
}
const context = {componentParent};
Live Demo

Testing if button changes state, or if component appears (React)

I have a component with a button and a form. When button is visible, the form is hidden and the opposite - when we click button it dissapears and form is shown. I would like to test it either with enzyme or testing-library, but all my tests fail.
import React, { useState } from 'react';
import Form from './Form';
const FormComponent = () => {
const [isFormVisible, setFormVisibility] = useState(false);
function toggleFormVisibility() {
setFormVisibility(!isFormVisible);
}
return (
<section>
{!isFormVisible && (
<button
id='toggle-form-button'
data-testid='toggle-form-button'
onClick={toggleFormVisibility}
>
Show form
</button>
)}
{isFormVisible && <Form onCancel={toggleFormVisibility} />}
</section>
);
};
export default FormComponent;
My test:
describe('Form component', () => {
it('should fire toggle form action on button click', () => {
const setState = jest.fn();
const useStateSpy = jest.spyOn(React, 'useState');
useStateSpy.mockImplementation(() => [undefined, setState]);
const component = render(
<Form />
);
const showFormButton = component.getByTestId('toggle-form-button');
Simulate.click(showFormButton);
expect(showFormButton).toBeCalled();
});
});
and another one:
it('should fire toggle form action on button click', () => {
const toggleFormVisibility = jest.fn();
const component = render(
<Form />
);
const showFormButton = component.getByTestId('toggle-form-button');
Simulate.click(showFormButton);
expect(toggleFormVisibility).toBeCalled();
});
It looks like in your tests, you are trying to render the <Form> instead of the <FormComponent>, that might be causing the problem in your test.
Also in your 2nd test, you are not setting up the toggleFormVisibility mocked function with your component, so that wouldn't be invoked at all, the answer above is pretty reasonable, you might want to consider giving that a shot, not sure why it gets downvoted.
testing-library may make this test easier:
import { render, fireEvent } from '#testing-library/react'
render(<Form />);
fireEvent.click(screen.getByLabelText('Show form'));

Resources