React Unit testing onClick event - javascript

I have a Button wrapper component in which I am using mui button. I want to do the unit testing for this button wrapper component. I wrote some code but for onClick test it is falling.
index.tsx (ButtonWrapper Component)
import React from 'react';
import { Button } from '#material-ui/core';
import { ButtonProps } from '../../../model';
type ConfigButtonProps ={
// variant?: string,
// color?: string,
// fullWidth?: boolean,
// type?: string
}
export const ButtonWrapper = (props: ButtonProps) => {
const {children, onSubmit, disabled, type, onClick, ...otherprops} = props
console.log("button", otherprops, type);
const configButton:ConfigButtonProps = {
variant: 'contained',
color: 'primary',
fullWidth: true,
type: type
}
return (
<Button disabled={disabled} onClick={onSubmit} {...configButton}>
{children}
</Button>
);
};
index.test.tsx (Button Wrapper test)
import { ButtonWrapper } from "./index"
import { fireEvent, render, screen } from "#testing-library/react";
import { ButtonProps } from "../../../model";
const makeSut = (props: ButtonProps) => {
return render(<ButtonWrapper onClick={jest.fn()} {...props} />);
};
describe("<ButtonWrapper />", () => {
test("Button renders correctly",()=>{
render(<ButtonWrapper />)
const buttonElem = screen.getByRole('button')
expect(buttonElem).toBeInTheDocument()
})
test("Should call onClick successfully", () => {
const spy = jest.fn();
const { getByRole } = makeSut({ onClick: spy });
fireEvent.click(getByRole('button'));
expect(spy).toHaveBeenCalled();
});
});
FormContainer.tsx (Parent Container)
return (<form onSubmit={event=>this.onSubmit(event)}>
{/* <div>FormContainer {JSON.stringify(this.props.states, null, 2)}</div> */}
{this.state.fields.map((field,index)=>{
return <FormControl
key={field.id}
fieldConfig={field}
focused={(event:React.ChangeEvent<HTMLInputElement>)=>this.fieldBlur(event,field,index)}
changed={(event:React.ChangeEvent<HTMLInputElement>)=>this.fieldChange(event,field,index)} />
})}
<ButtonWrapper type='submit'>Submit</ButtonWrapper>
</form>)
Error
I also want to know in order to make 90% test coverage what else I need to test ?
[![enter image description here]]
I tried this below mentioned code also but the last line fails.
test("Should call onClick successfully", () => {
const onSubmitHandler = jest.fn();
render(<ButtonWrapper onClick={onSubmitHandler} />)
const buttonElement = screen.getByRole('button');
user.click(buttonElement)
expect(onSubmitHandler).toHaveBeenCalledTimes(1) //This line fails
});

Your spy function is coming in onClick, not the onSubmit prop:
const { getByRole } = makeSut({ onClick: spy });
And your component assigns the value from onSubmit to onClick:
<Button disabled={disabled} onClick={onSubmit} {...configButton}>
{children}
</Button>
About the coverage - I cannot see your coverage report but what I can see in your component - there is a disabled prop. You should render the component with true and false values for this prop. This should give you higher coverage.

Related

Mock antd useBreakpoint hook

I want to test the modal component, but there is an error with defining the cancel button,
it renders only if it's not mobile.
isMobile is a variable that is a boolean value from hook - useBreakpoint (ant design library hook).
I don't know how to mock that value, or how to click that button.
Note: if I remove the isMobile check, the button clicks well:)
import React from 'react'
import {Grid, Typography} from 'antd'
import {Button} from '#/components/Button'
import {Modal} from '#/components/Modal'
import translations from './translations'
import {ConfirmationModalProps} from './props'
const {Text} = Typography
const {useBreakpoint} = Grid
export const ConfirmationModal = ({visible, onClose, children}: ConfirmationModalProps) => {
const screens = useBreakpoint()
const isMobile = screens.xs
return (
<Modal
title={translations().chargeConfirmation}
visible={visible}
onOk={onClose}
onCancel={onClose}
footer={[
!isMobile && (
<Button role={'cancel-button'} type={'ghost'} key={'cancel'} onClick={onClose}>
{ translations().cancel }
</Button>
),
<Button type={'primary'} key={'charge'} onClick={onClose}>
{ translations().confirm }
</Button>
]}
>
<Text>{translations().confirmationText(children)}</Text>
</Modal>
)
}
describe('ConfirmationModal', () => {
it('should should the children and close button', async () => {
const onClose = jest.fn()
jest.mock('antd/es/grid/hooks/useBreakpoint', () => ({
xs: false
}))
render(<ConfirmationModal onClose={onClose} visible={true}>100</ConfirmationModal>)
const child = screen.getByText('Are you sure you want to charge 100')
expect(child).toBeTruthy()
expect(screen.queryByTestId('cancel')).toBeDefined()
await waitFor(() => screen.queryByTestId('cancel'))
fireEvent.click(screen.queryByRole('cancel-button'))
expect(onClose).toHaveBeenCalledTimes(1)
})
})
Errors are:
Error: Unable to fire a "click" event - please provide a DOM element.
Unable to find an accessible element with the role "cancel-button"
Depending on queryByRole or getByRole selector.
What is wrong?
Let's take a look at the source code of the useBreakpoint hook.
import { useEffect, useRef } from 'react';
import useForceUpdate from '../../_util/hooks/useForceUpdate';
import type { ScreenMap } from '../../_util/responsiveObserve';
import ResponsiveObserve from '../../_util/responsiveObserve';
function useBreakpoint(refreshOnChange: boolean = true): ScreenMap {
const screensRef = useRef<ScreenMap>({});
const forceUpdate = useForceUpdate();
useEffect(() => {
const token = ResponsiveObserve.subscribe(supportScreens => {
screensRef.current = supportScreens;
if (refreshOnChange) {
forceUpdate();
}
});
return () => ResponsiveObserve.unsubscribe(token);
}, []);
return screensRef.current;
}
export default useBreakpoint;
It uses ResponsiveObserve.subscribe() to get the supportScreens, it calls ResponsiveObserve.register(), the .register() method use window.matchMedia() underly. jestjs use JSDOM(a DOM implementation) as its test environment, but JSDOM does not implement window.matchMedia() yet. So we need to mock it, see Mocking methods which are not implemented in JSDOM
E.g.
import { render } from '#testing-library/react';
import React from 'react';
import { Grid } from 'antd';
const { useBreakpoint } = Grid;
describe('72021761', () => {
test('should pass', () => {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(
(query) =>
({
addListener: (cb: (e: { matches: boolean }) => void) => {
cb({ matches: query === '(max-width: 575px)' });
},
removeListener: jest.fn(),
matches: query === '(max-width: 575px)',
} as any)
),
});
let screensVar;
function Demo() {
const screens = useBreakpoint();
screensVar = screens;
return <div />;
}
render(<Demo />);
expect(screensVar).toEqual({
xs: true,
sm: false,
md: false,
lg: false,
xl: false,
xxl: false,
});
});
});

React memo creates rerender

I'm having an issue with react memo when using nextjs. In the _app e.g. I have a button imported:
import { ChildComponent } from './ChildComponent';
export const Button = ({ classN }: { classN?: string }) => {
const [counter, setCounter] = useState(1);
const Parent = () => {
<button onClick={() => setCounter(counter + 1)}>Click me</button>
}
return (
<div>
{counter}
<Parent />
<ChildComponent />
</div>
);
};
Child component:
import React from 'react';
export const ChildComponent = React.memo(
() => {
React.useEffect(() => {
console.log('rerender child component');
}, []);
return <p>Prevent rerender</p>;
},
() => false
);
I made one working in React couldn't figure it out in my own app:
https://codesandbox.io/s/objective-goldwasser-83vb4?file=/src/ChildComponent.js
The second argument of React.memo() must be a function that returns true if the component don't need to be rerendered and false otherwise - or in the original definition, if the old props and the new props are equal or not.
So, in your code, the solution should be just change the second argument to:
export const ChildComponent = React.memo(
() => { ... },
// this
() => true
);
Which is gonna tell React that "the props didn't change and thus don't need to rerender this component".
So my issue was that I made a function called Button and returned inside a button or Link. So I had a mouseEnter inside the button which would update the state and handle the function outside the function. Kinda embarrassing. This fixed it. So the only change was I moved usestate and handlemousehover inside the button function.
const Button = () => {
const [hover, setHover] = useState(false);
const handleMouseHover = (e: React.MouseEvent<HTMLElement>) => {
if (e.type === 'mouseenter') {
setHover(true);
} else if (e.type === 'mouseleave') setHover(false);
};
return (
<StyledPrimaryButton
onMouseEnter={(e) => handleMouseHover(e)}
onMouseLeave={(e) => handleMouseHover(e)}
>
<StyledTypography
tag="span"
size="typo-20"
>
{title}
</StyledTypography>
<ChildComponent />
</StyledPrimaryButton>
);
};

How to set the state using context.provider in react and typescript?

i am using context.provider usecontext reacthook to show a dialog. i set this around MainComponent. For the value attribute of context.provider i get error type {setDialogOpen(Open: boolean) => void} is not assignable to type boolean.
what i am trying to do?
I want to display a dialog when user clicks either a button in home or books component. on clicking hide button in dialog the dialog shouldnt be open.
below is my code,
function MainComponent() {
const DialogContext = React.createContext(false);
let [showDialog, setShowDialog] = React.useState(false);
return (
<DialogContext.Provider value={{
setDialogOpen: (open: boolean) => setShowDialog(open)}}>//get error
{showDialog && <Dialog DialogContext={DialogContext}/>
<Route
path="/items">
<Home DialogContext={DialogContext}/>
</Route>
<Route
path="/id/item_id">
<Books DialogContext={DialogContext}/>
</Route>
</DialogContext.Provider>
)
}
function Home({DialogContext} : Props) {
const dialogContext= React.useContext(DialogContext);
const handleClick = (dialogContext: any) {
dialogContext.setDialogOpen(true);
}
return (
<button onClick={handleClick(dialogContext)}>button1</button>
)
}
function Books({DialogContext} : Props) {
const dialogContext= React.useContext(DialogContext);
const handleClick = (dialogContext: any) {
dialogContext.setDialogOpen(true);
}
return (
<button onClick={handleClick(dialogContext)}>button2</button>
)
}
function Dialog({DialogContext}: Props) {
return(
<div>
//sometext
<button> hide</button>
</div>
)
}
I have tried something like below,
return (
<DialogContext.Provider value={{
setShowDialog(open)}}>//still get a error
{showDialog && <Dialog DialogContext={DialogContext}/>
)
Could someone help me fix this or provide a better approach to show the dialog on clicking a button in home and books component using usecontext hook. thanks.
There are few issues that you have to fix in your code.
You are creating context with the default value of false. Then later you try to override it to an object and hence the type error.
To fix the issue, create & export the context in separate file/helper. Don't pass them down as props.
import the context in parent and child components.
your handleClick fun in child component is missing an arrow.
the button onClick in child component is directly calling the function. You should pass just the function reference.
See the updated code with corrections below.
context helper
...
type ContextProps = {
setDialogOpen?: (open: boolean) => void,
};
export const DialogContext = React.createContext<ContextProps>({});
MainComponent
import {DialogContext} from '../contextHelper';
function MainComponent() {
// const DialogContext = React.createContext(false); //<---- remove this
let [showDialog, setShowDialog] = React.useState(false);
return (
<DialogContext.Provider value={{
setDialogOpen: (open: boolean) => setShowDialog(open)}}>
...
Home & Book Component
import {DialogContext} from '../contextHelper';
function Home() {
const dialogContext= React.useContext(DialogContext);
const handleClick = () => {
dialogContext.setDialogOpen(true);
}
return (
<button onClick={handleClick}>button1</button>
)
}
import {DialogContext} from '../contextHelper';
function Books() {
const dialogContext= React.useContext(DialogContext);
const handleClick = () => {
dialogContext.setDialogOpen(true);
}
return (
<button onClick={handleClick}>button2</button>
)
}

Enzyme mount wrapper is empty after simulate('click') in ReactApp

I'm trying to test a registration component that has a Vertical Stepper with Jest/Enzyme and I keep hitting a wall when trying to simulate the user clicking "Next" .
expected behavior is to do nothing if the "Required" input fields are empty, however after doing the .simulate('click') following assertions fail with not finding any html in the wrapper.
The component is passed through react-redux connect() so I don't know if that would be related.
UserRegistration.js
import React from 'react';
import { connect } from 'react-redux';
import Stepper from '#material-ui/core/Stepper';
import Step from '#material-ui/core/Step;
import StepLabel from '#material-ui/core/StepLabel;
import StepContent from '#material-ui/core/StepContent'
class UserRegistration extends React.Component {
constructor(props){
this.state = {
activeStep: 0,
inputData: {},
...
}
}
getStepContent = () => {
switch(this.state.activeStep)
case '...':
return
(<>
<input test-data="firstName"/>
...
</>);
...
}
render () {
const steps = ['Personal Info', 'Corporate Details', ...]
return (
<Stepper activeStep={this.state.activeStep} orientation="vertical">
{steps.map((label, index) => {
return (
<Step key={index}/>
<StepLabel>{label}</StepLabel>
<StepContent>
{this.getStepContent()}
<button data-test="btn-next" onClick={() => this.goNext()}> NEXT </button>
<button onClick={() => this.goBack()}> BACK </button>
)
}
}
</Stepper>
)
}
}
const mapStateToProps = () => {...}
const mapDispatchToProps = () => {...}
export default connect(mapStateToProps, mapDispatchToProps)(UserRegistration)
UserRegistration.test.js
const wrapper = mount(
<Provider store={store}
<UserCreate/>
</Provider>
)
it('Confirm REQUIRED fields rendered', () => {
expect(wrapper.find("input[data-test='firstName']").length).toEqual(1);
// PASS
});
it('Check if still on same step clicked NEXT with no user data', () => {
wrapper.find("button[data-test='btn-next']").simulate('click');
expect(wrapper.find("input[data-test='firstName']").length).toEqual(1);
// Expected value to equal: 1, Received: 0
})
Same outcome regardless of the element I'm looking up.
Any suggestions will be greatly appreciated.
You need to update. So you would change it:
it('Check if still on same step clicked NEXT with no user data', () => {
wrapper.find("button[data-test='btn-next']").simulate('click');
// Add this line
wrapper.update();
const button = wrapper.find("input[data-test='firstName']");
expect(button.length).toEqual(1);
// Expected value to equal: 1, Received: 0
});
Then the test should work as you intend.

Test properties that injected by React Redux

I have a component that renders a button if a property errorMessage is not null.
class App extends Component {
static propTypes = {
// Injected by React Redux
errorMessage: PropTypes.string,
resetErrorMessage: PropTypes.func.isRequired,
};
renderErrorMessage() {
const { errorMessage } = this.props;
if (!errorMessage) return null;
return (
<p id="error-message">
<b>{errorMessage}</b>{' '}
<button id="dismiss" onClick={this.props.resetErrorMessage()}>
Dismiss
</button>
</p>
);
}
render() {
return (
<div className="app">
{this.renderErrorMessage()}
</div>
);
}
}
The property injected by React Redux:
import { connect } from 'react-redux';
import App from '../components/App/App';
const mapStateToProps = (state, ownProps) => ({
errorMessage: state.errorMessage,
});
export default connect(mapStateToProps, {
resetErrorMessage: () => ({
type: 'RESET_ERROR_MESSAGE',
})
})(App);
As you can see I also have resetErrorMessage that clears errorMessage:
const errorMessage = (state = null, action) => {
const { type, error } = action;
if (type === RESET_ERROR_MESSAGE) {
return null;
} else if (error) {
return error;
}
return state;
};
How can I test my component and say if I click the button then button hides or if errorMessage is not null button shows?
I want to get something like this:
const props = {
errorMessage: 'Service Unavailable',
resetErrorMessage,
};
it('renders error message', () => {
const wrapper = shallow(<App {...props} />);
expect(wrapper.find('#error-message').length).toBe(1);
wrapper.find('#dismiss').simulate('click');
expect(wrapper.find('#error-message').length).toBe(0);
});
But now my problem is that if I simulate click to dismiss button - error message doesn't hide.
As I posted in the previous question you deleted, if you want to test button clicks your best bet would be to call the 'unconnected' component. If you want to test the connected component, then you have to pass a mockstore into it like so.
const wrapper = shallow(<App {...props} store={store} />);
So import the app in your test and just pass the resetErrorMessage function as a mocked function, such as what you do with jest.
const resetErrorMessage = jest.fn(() => {});
const wrapper = shallow(<App {...props} resetErrorMessage={resetErrorMessage} />);
wrapper.find('#dismiss').simulate('click');
expect(resetErrorMessage).toHaveBeenCalled();
My advice would be to only test the connected component when you want to manipulate directly from store changes.

Categories

Resources