I'm new with testing-library and jest and I'm trying to test a function inside of the component that changes the value of an input. The component is a form with another component that it's an input.
export const Form = () => {
const [name, setName] = useState("");
const handleOnSubmit = e => {
e.preventDefault();
const form = e.target;
};
const inputChange = (param) => (e) => {
const inputValue = e.target.value;
setName(inputValue);
};
return (
<form className="form" onSubmit={handleOnSubmit}>
<InputGroup text="name" type="text" value={name} functionality={inputChange("name")}/>
<Button type="submit" disabled={name === undefined}/>
</form>
);
};
export default Form;
The InputGroup Component looks like this
export const InputGroup = ({type, id, value, required, functionality, text}) => {
return (
<label>{text}</label>
<input className="input" type={type} id={id} name={id} value={value}
required={required} onChange={functionality}
/>
);
};
I have tried something like this, but I'm not pretty sure on how to test a function that is directly on the component Form and that it's being passed to the component InputGroup.
describe("Form", () => {
let value;
let component;
const handleSubmit = jest.fn();
const handleChange = ev => {
ev.preventDefault();
value = ev.currentTarget.value;
}
beforeEach(() => {
component = render(
<Form onSubmit={handleSubmit} functionality={handleChange} />
);
});
it("check error name is triggered", () => {
const input = component.getByText("name");
fireEvent.change(input, {target: {value: "aaa"}});
});
});
I get an error thats says "The given element does not have a value setter", so how can I pass the inputChange function to the InputGroup Component?
Ok, thanks for sharing the InputGroup. So you can test the InputGroup easily.
describe("InputGroup", () => {
it("check error name is triggered", () => {
const fn = jest.fn()
render(<InputGroup functionality={functionality} />)
fireEvent.change(input, {target: {value: "aaa"}});
expect(fn).toHaveBeenLastCalledWith(...)
});
});
Just an idea. The above code might not run as posted. Ok, now comes to the Form. The step might be similar but it might take you some time to get around, but you don't need to test the functionality again, simply because this prop has nothing to do with Form. From the form perspective, it only cares onSubmit, so you can test against that in the similar way that posted earlier.
Related
I'm trying to apply a unit test in my custom input component
If I pass the value prop in the <Input /> in the render function, the test fails.
Does anyone know the reason?
In controlled components like this input, what we can test to have valid unit tests?
Thanks
Input.tsx
import React, {ChangeEvent, FunctionComponent} from 'react';
import styles from './Input.module.css'
export interface InputProps {
type?: string
disabled?: boolean
value?: string
onChange?: (value: string) => void
}
const Input: FunctionComponent<InputProps> = ({
type= 'text',
disabled = false,
value,
onChange,
}) => {
const handleOnChange = (e: ChangeEvent<HTMLInputElement>) => {
const value = e.currentTarget.value
if (onChange) {
onChange(value)
}
}
return (
<div className={styles.inputWrapper}>
<input
className={styles.input}
type={type}
disabled={disabled}
value={value}
onChange={handleOnChange}
/>
</div>
);
}
export default Input;
Input.test.tsx
// PASS WITHOUT ANY ERRORS
it('should has the new value', async () => {
const user = userEvent.setup()
const onChangeMock = jest.fn();
const { getByRole } = render(<Input onChange={onChangeMock} />)
const input = getByRole('textbox')
expect(input).toHaveValue('')
await user.type(input, 'new input value')
expect(input).toHaveValue('new input value')
})
// FAILS
it('should has the new value', async () => {
const user = userEvent.setup()
const onChangeMock = jest.fn();
const { getByRole } = render(<Input value="" onChange={onChangeMock} />)
const input = getByRole('textbox')
expect(input).toHaveValue('')
await user.type(input, 'new input value')
expect(input).toHaveValue('new input value')
})
You can use rerender function that is returned from render.
With this, you send new value into your component, input has a new value and then you can assert for that value in the input.
In your case, your test needs to have also checking if onChange method is called when you do userEvent.type() or if that does not work you can use fireEvent.change(input...).
it('should has the new value', async () => {
const user = userEvent.setup();
const onChangeMock = jest.fn();
const { getByRole, rerender } = render(<Input value="" onChange={onChangeMock} />);
const input = getByRole('textbox');
expect(input).toHaveValue('');
rerender(<Input value="new input value" onChange={onChangeMock} />);
expect(input).toHaveValue('new input value');
});
I am trying to build a small app to test my jest and enzyme knowledge. However, I have run into an issue.
I have the following Homepage.js:
const Homepage = props => {
const [input, setInput] = React.useState({
type: 'input',
config: {
required: true,
placeholder: 'Type a GitHub username'
},
value: ''
});
const onChangeInput = event => {
setInput(prevState => {
return {
...prevState,
value: event.target.value
};
});
};
return (
<section className={styles.Homepage}>
<form className={styles.SearchBox} onSubmit={(event) => props.getUser(event, input.value)} data-test="component-searchBox">
<h4>Find a GitHub user</h4>
<Input {...input} action={onChangeInput}/>
{props.error ? <p>{`Error: ${props.error}`}</p> : null}
<Button>Submit</Button>
</form>
</section>
);
};
I want to test that the input field fires a function when I type in it. The Input.js component is the following:
const input = props => {
switch (props.type) {
case 'input':
return <input className={styles.Input} {...props.config} value={props.value} onChange={props.action} data-test="component-input"/>
default: return null;
};
};
You can find my test below:
const mountSetup = () => {
const mockGetUser = jest.fn()
return mount(
<Homepage type='input' getUser={mockGetUser}>
<Input type='input'/>
</Homepage>
);
};
test('State updates with input box upon change', () => {
const mockSetInput = jest.fn();
React.useState = jest.fn(() => ["", mockSetInput]);
const wrapper = mountSetup();
const inputBox = findByTestAttr(wrapper, 'component-input');
inputBox.simulate("change");
expect(mockSetInput).toHaveBeenCalled();
});
The problem here is that in the Input.js the switch is always returning null even though I am passing the props type='input'. As such I get the error Method “simulate” is meant to be run on 1 node. 0 found instead.
Can someone help me with this?
Thanks
You need not pass the Input inside the HomePage. Homepage has input child and it renders
<Homepage type='input' getUser={mockGetUser}>
</Homepage>
You can try passing the data in the react Usestate mock.
React.useState = jest.fn(() => [{
type: 'input'
}, mockSetInput]);
I have a simple functional component which I need to test.
const Product = () => {
const handleOnChange = (value) => {
console.log(value);
}
return (
<div>
<input type="text" onChange={(e) => {handleOnChange(e.target.value)}} />
</div>
)
}
I'd like to test if "handleOnChange" function is called when the input changes its value. I tried that:
let wrapper;
beforeEach(() => {
wrapper = shallow(<Product />);
});
describe('Product interactions', () => {
it('should call handleOnChange function on input change', () => {
const mockedhandleOnChange = jest.fn();
wrapper.handleOnChange = mockedhandleOnChange;
wrapper.find('input').simulate('change', {target: {value: 10}});
expect(mockedhandleOnChange).toHaveBeenCalledTimes(1);
});
});
Of course it doesn't work as I cannot reach the function via "wrapper.handleOnChange".
Please help!
it('should call handleOnChange function on input change', () => {
const wrapper = shallow(<Product />);
const input = wrapper.find('input');
input.simulate('change', { target: { value: 10 } });
input = wrapper.find('input');
expect(input.props().value).toEqual(10);
});
You should make React state single source of truth. Currently, input in your program is maintaining its own state. Better option would be to use it as Controlled Components. Once you are using input as a controlled component, your program would be something like below:
class Product extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
}
handleOnChange = (value) => {
this.setState({ value })
}
return (
<div>
<input id="input1" type="text" value={this.state.value} onChange={(e) => {handleOnChange(e.target.value)}} />
</div>
)
}
Once you have the above code, it will be much simpler to do validation on input and also to test. You need to call onChange of input, after which you can validate state. Your test will look something like below:
let wrapper;
beforeEach(() => {
wrapper = shallow(<Product />);
});
describe('Product interactions', () => {
it('should call handleOnChange function on input change', () => {
wrapper.find('#input1').getNode().props.onChange({
target: { value: '123' }
});
expect(wrapper.state().value).toEqual('123');
});
});
I'm relatively new to Jest and testing in general. I have a component with an input element:
import * as React from "react";
export interface inputProps{
placeholder: string;
className: string;
value: string;
onSearch: (depID: string) => void;
}
onSearch(event: any){
event.preventDefault();
//the actual onclick event is in another Component
this.props.onSearch(event.target.value.trim());
}
export class InputBox extends React.Component<inputProps, searchState> {
render() {
return (
<input
onChange={this.onSearch} //need to test this
className={this.props.className}
type="text"
value={this.props.value}
placeholder={this.props.placeholder} />
);
}
}
I want a test that checks that input element's onChange is a function that takes in the input element's value attribute as the parameter. This is how far I have gotten so far:
//test to see the input element's onchange
//returns a function that takes its value as a param
it("onChange param is the same value as the input value", () => {
const mockFn = jest.fn();
const input = enzyme.shallow(<InputBox
value="TestVal"
placeholder=""
className=""
onSearch={mockFn}/>);
input.find('input').simulate('change', { preventDefault() {} });
expect(mockFn.mock.calls).toBe("TestVal");
});
I am going off of the first solution here Simulate a button click in Jest
And: https://facebook.github.io/jest/docs/en/mock-functions.html
Edit: Running the above throws the following error:
TypeError: Cannot read property 'value' of undefined
Syntax on your code snippet I think should be:
import React from 'react';
export default class InputBox extends React.Component {
onSearch(event) {
event.preventDefault();
this.props.onSearch(event.target.value.trim());
}
render () { return (<input onChange={this.onSearch.bind(this)} />); }
}
The test is failing because, as same you define the preventDefault function on the event object, you also must define other properties used on the onSearch function.
it('should call onChange prop', () => {
const onSearchMock = jest.fn();
const event = {
preventDefault() {},
target: { value: 'the-value' }
};
const component = enzyme.shallow(<InputBox onSearch={onSearchMock} />);
component.find('input').simulate('change', event);
expect(onSearchMock).toBeCalledWith('the-value');
});
Previous test code needs to define the event shape because you are using shallow rendering. If you want instead to test that the actual input value is being used on your onSearch function you need to try a full render with enzyme.mount:
it('should call onChange prop with input value', () => {
const onSearchMock = jest.fn();
const component = enzyme.mount(<InputBox onSearch={onSearchMock} value="custom value" />);
component.find('input').simulate('change');
expect(onSearchMock).toBeCalledWith('custom value');
});
For those testing using TypeScript (and borrowing from the answers above), you'll need to perform a type coercion (as React.ChangeEvent<HTMLInputElement>) to ensure that the linter can view the signature as being compatible:
React file
export class InputBox extends React.Component<inputProps, searchState> {
onSearch(event: React.ChangeEvent<HTMLInputElement>){
event.preventDefault();
//the actual onclick event is in another Component
this.props.onSearch(event.target.value.trim());
}
render() {
return (
<input
onChange={this.onSearch} //need to test this
className={this.props.className}
type="text"
value={this.props.value}
placeholder={this.props.placeholder} />
);
}
}
Test file
it('should call onChange prop', () => {
const onSearchMock = jest.fn();
const event = {
target: { value: 'the-value' }
} as React.ChangeEvent<HTMLInputElement>;
const component = enzyme.shallow(<InputBox onSearch={onSearchMock} />);
component.find('input').simulate('change', event);
expect(onSearchMock).toBeCalledWith('the-value');
});
or alternatively
it('should call onChange prop', () => {
const onSearchMock = jest.fn();
const event = {
target: { value: 'the-value' }
} as React.ChangeEvent<HTMLInputElement>;
const component = enzyme.mount<InputBox>(<InputBox onSearch={onSearchMock} />);
const instance = component.instance();
instance.onSearch(event);
expect(onSearchMock).toBeCalledWith('the-value');
});
I figured out the solution.
So, instead of passing in the value inside InputBox, we have to pass it inside the second param of simulate as shown below. Then we simply check for equality against the first arg of the first call to the mockFn. Also, we can get rid of the event.preventDefault();
it("onChange param is the same value as the input element's value property", () => {
const mockFn = jest.fn();
const input = enzyme.shallow(<InputBox
value=""
placeholder=""
className=""
onSearch={mockFn}/>);
input.find('input').simulate('change', {target: {value: 'matched'} });
expect(mockFn.mock.calls[0][0]).toBe('matched');
});
How about this one? I simulate the change event using enzyme and perform a snapshot test.
Component
import React, { FunctionComponent, useState } from 'react';
const Index: FunctionComponent = () => {
const [val, setVal] = useState('');
const onInputChange = e => {
e.preventDefault();
setVal(e.target.value);
};
return (
<input type='text' onChange={onInputChange} value={val} />
);
};
export default Index;
Unit Test
describe('Index with enzyme', () => {
it('Should set value to state when input is changed', () => {
const container = shallow(<Index />);
const input = container.find('input');
input.simulate('change', { preventDefault: jest.fn, target: { value: "foo" } });
expect(container).toMatchSnapshot();
});
});
Snapshot
exports[`Index with enzyme Should set value to state when input is changed 1`] = `
<input
onChange={[Function]}
type="text"
value="foo"
/>
`;
I struggled with this for hours. Plus since I had multiple select fields on one page. What I found is that Textfield solution works differently from Select.test given on docs.
On the code I defined SelectProps with id. (You can also go with data-testid)
I could only trigger dropdown by clicking this field.
<TextField
select
variant = "outlined"
value = { input.value || Number(0) }
onChange = { value => input.onChange(value) }
error = { Boolean(meta.touched && meta.error) }
open = { open }
SelectProps = {
{
id: `${input.name}-select`,
MenuProps: {
anchorOrigin: {
vertical: "bottom",
horizontal: "left"
},
transformOrigin: {
vertical: "top",
horizontal: "left"
},
getContentAnchorEl: null
}
}
}
{ ...props} >
//yourOptions Goes here
</TextField>
And in my test.
const pickUpAddress = document.getElementById("address-select");
UserEvent.click(pickUpAddress);
UserEvent.click(screen.getByTestId("address-select-option-0"));
Worked like a charm afterwards. Hope this helps.
If you're writing lwc (salesforce) jest tests you can simulate this by selecting the input and dispatching an event.
const changeEvent = new CustomEvent('change', {
detail: {
'value': 'bad name'
}
});
element.shadowRoot.querySelector('lightning-input').dispatchEvent(changeEvent);
I have to following component:
import React from 'react';
const SearchInput = ({className, onChange}) => {
const onTextInputChange = (e) => {
const value = e.target.value;
onChange(value);
};
return (
<textarea
className={className} onChange={onTextInputChange}>
</textarea>
)
};
export default SearchInput;
But after filling some text, and then deleting it, the previous page is reloaded. How can I prevent this from happening?
Add event.preventDefault() in your function:
const SearchInput = ({className, onChange}) => {
const onTextInputChange = (e) => {
e.preventDefault();
const value = e.target.value;
onChange(value);
};
return (
<textarea
className={className} onChange={(e) => onTextInputChange}>
</textarea>
)
};
I found the answer! apparently on the onChange from the parent component, I did a comparison between String and Array, it throws an exception that lead to the page reloading.
Thanks #Andrew for directing me in this direction.