Cannot read property 'value' when simulating a form submit - reactjs

I am trying to do a complete istanbul coverage test with jest. At this moment I have a component almost all tested but there is a handleSubmit function where I make a dispatch receiving form event data and when I run the test it tells me
TypeError: Cannot read property 'value' of undefined
10 | payload: {
11 | name: name.value,
> 12 | item: item.value,
| ^
13 | status: status.value }
14 | })
15 | }
I am loading a mockstore, mounted all the component, its all tested but the submit still fails. My test function is as simple as:
it('testing submit', () => {
const form = component.find(`[data-test="submit"]`).first()
form.simulate('submit')
... and continues expecting some existences, but there aren't problems there
I already tried this: enzyme simulate submit form, Cannot read property 'value' of undefined
And tried to parse the event values in the simulate action...
The complete module code is...
class Filters extends Component {
handleSubmit = event => {
event.preventDefault()
const {name, items, status} = event.target;
this.props.dispatch({
type: 'SEARCH_PLAYER',
payload: {
name: name.value,
item: item.value,
status: status.value }
})
}
render() {
return(
<div>
<form onSubmit={this.handleSubmit} data-test="submit">
<div className="form-group col-md-12 text-center"> ...
Another really crazy thing is that my test recognize the "event.target.name.value" and not the items and status. In fact if i delete items and status from the dispatch the test runs successfully.

Looks like you are using item on line 12, but extracting items from the event.target.

The way you chose to handle values is a bit strange. Instead, handle values through state like so: Controlled Components
Then you can test that this.props.dispatch() was called with the correct values.
Side note: Avoid using data attributes when unnecessary, as they'll start to clog up your DOM with superfluous attributes. You have plenty of options to find by element, element.className, className, ...and so on.
Working example: https://codesandbox.io/s/5j4474rkk (you can run the test defined below by clicking on the Tests tab at the bottom left of the screen.
components/Form/Form.js
import React, { Component } from "react";
import PropTypes from "prop-types";
export default class Form extends Component {
state = {
test: ""
};
static propTypes = {
dispatch: PropTypes.func.isRequired
};
handleChange = ({ target: { name, value } }) => {
this.setState({ [name]: value });
};
handleSubmit = e => {
e.preventDefault();
this.props.dispatch({
type: "SEARCH_PLAYER",
payload: {
test: this.state.test
}
});
};
render = () => (
<form onSubmit={this.handleSubmit} className="form-container">
<h1>Form Testing</h1>
<input
className="uk-input input"
type="text"
name="test"
placeholder="Type something..."
onChange={this.handleChange}
value={this.state.test}
/>
<button type="submit" className="uk-button uk-button-primary submit">
Submit
</button>
</form>
);
}
components/Form/__tests__/Form.js (shallowWrap and checkProps are custom functions that can be found in test/utils/index.js)
import React from "react";
import { shallowWrap, checkProps } from "../../../test/utils";
import Form from "../Form";
const dispatch = jest.fn();
const initialProps = {
dispatch
};
const initialState = {
test: ""
};
const wrapper = shallowWrap(<Form {...initialProps} />, initialState);
describe("Form", () => {
it("renders without errors", () => {
const formComponent = wrapper.find(".form-container");
expect(formComponent).toHaveLength(1);
});
it("does not throw PropType warnings", () => {
checkProps(Form, initialProps);
});
it("submits correct values to dispatch", () => {
const name = "test";
const value = "Hello World!";
const finalValues = {
type: "SEARCH_PLAYER",
payload: {
[name]: value
}
};
wrapper.find("input").simulate("change", { target: { name, value } }); // simulates an input onChange event with supplied: name (event.target.name) and value (event.target.value)
wrapper
.find(".form-container")
.simulate("submit", { preventDefault: () => null }); // simulates a form submission that has a mocked preventDefault (event.preventDefault()) to avoid errors about it being undefined upon form submission
expect(dispatch).toBeCalledWith(finalValues); // expect dispatch to be called with the values defined above
});
});

Related

Render data in React Hooks

Hello I'm try to Render data in a component to another component, which are siblings to one another. with useState Hook(rff) based on component code (rcf)
index.js -> is entry point, that calls only one component App, as we have no route
App.js -> is the parent component, which has two child, Certification and Panel
Certification.js -> takes input
Panel -> renders data from certification
I know i have problem with handleFromCert (this is my handle change function)
here my code -rff
https://codesandbox.io/s/zen-paper-gil-xcyj3?file=/src/
here the code that based on rcf and work fine
https://codesandbox.io/s/elegant-shtern-362ki?file=/src/
I corrected the code and now it works!
handleFromCert in App.js should receive name and value;
value2 in the Panel component in App.js is passed with an error;
handleFromCert in Certifications.js setValue changes incorrectly.
Certifications.js
import React, { useState } from "react";
const Certifications = (props) => {
const [value, setValue] = useState({
value1: "",
value2: ""
});
const handleFromCert = ({ target: { value, name } }) => {
setValue(prevState => ({ ...prevState, [name]: value }));
props.handleFromCert(name, value);
};
return (
<div>
<input name="value1" onChange={handleFromCert} />
<input name="value2" onChange={handleFromCert} />
<div>
Inside certificate
<div>{value.value1}</div>
<div>{value.value2}</div>
Certificate ends
</div>
</div>
);
};
export default Certifications;
App.js
import React, { useState } from "react";
import Certifications from "./Certifications";
import Panel from "./Panel";
const App = () => {
const [value, setValue] = useState({
value1: "",
value2: ""
});
const handleFromCert = (name, value) =>
setValue((prevState) => ({ ...prevState, [name]: value }));
return (
<div>
{value.value1}
{value.value2}
<Certifications handleFromCert={handleFromCert} />
<Panel value1={value.value1} value2={value.value2} />
</div>
);
};
export default App;
The problem is that you're not passing the event as the argument, you're passing the value and your function is expecting the event. In your Certification component change this:
const handleFromCert = (e) => {
setValue({
[e.target.name]: e.target.value
});
props.handleFromCert((e.target.name, e.target.value));
};
To this:
const handleFromCert = (e) => {
setValue({
[e.target.name]: e.target.value
});
props.handleFromCert(e);
};
Your function handleFromCert is expecting the event, and you're just passing the value which is a string and cannot be destructured like the event.
Here's the sandbox working for me:
https://codesandbox.io/s/zen-paper-gil-forked-r01fh

Unit test form submission with data using react testing library

I have a react component with a form. I want to unit test (using jest and RTL) if form gets submitted with correct data. Here are my component and unit test method:
Component:
class AddDeviceModal extends Component {
handleOnSave(event) {
const { deviceName } = event.target;
const formData = {
deviceName: deviceName.value,
};
this.props.onSave(formData);
}
render() {
return (
<Form onSubmit={this.handleOnSave}>
<Form.Label>Device Name</Form.Label>
<Form.Control name="deviceName" placeholder="Device Name" required />
<Button type="submit">Save Device</Button>
</Form>
);
}
}
Unit Test:
it("Test form submit and validation", () => {
const handleSave = jest.fn();
const props = {
onSave: handleSave,
};
render(<AddDeviceModal {...props} />);
const deviceNameInput = screen.getByPlaceholderText(/device name/i);
fireEvent.change(deviceNameInput, { target: { value: "AP VII C2230" } });
fireEvent.click(getByText(/save device/i));
});
However, in handleOnSave(), I get error as deviceName is undefined. For some reason, it is not able to get the textbox value from event.target. Am I doing something wrong in above code? Needed help in fixing this issue.
The problem you have it with trying to access the input directly from event.target. You should access it from event.target.elements instead: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements.
function handleOnSave(event) {
event.preventDefault();
const { deviceName } = event.target.elements;
const formData = {
deviceName: deviceName.value
};
// this will log the correct formData even in tests now
console.log(formData);
this.props.onSave(formData);
}
And here is your test:
it("Test form submit and validation", () => {
const { getByPlaceholderText, getByText } = render(<App />);
const deviceNameInput = getByPlaceholderText(/device name/i);
fireEvent.change(deviceNameInput, { target: { value: "AP VII C2230" } });
fireEvent.click(getByText(/Save Device/i));
});
I created a codesandbox where you can see this in action: https://codesandbox.io/s/form-submit-react-testing-library-45pt8?file=/src/App.js

TypeError: Cannot read property 'map' of undefined (jest.js)

I have a component that has an input and a button. When a user types a hobby in the input, it is suppose to send that string to be updated to an api. I have set up my test and I am testing whether or not the component exists and I am getting the error TypeError: Cannot read property 'map' of undefined, when I console.log(component). It says that the component is undefined.
When I comment out the {this.state.hobbies.map()} section (including the second render and everything inside of that), the component is able to render.
EditProfile.js
import React, { Component } from 'react';
import { MdDelete } from 'react-icons/md';
import { updateHobbies } from '../../services/updateHobbies';
import './edit_profile.scss';
import PropTypes from 'prop-types';
class EditProfile extends Component {
state = {
hobbies: this.props.employeeHobbies,
userInput: ''
};
handleChange = e => {
this.setState({ userInput: e.target.value });
};
handleButtonClick = () => {
const hobby = this.state.hobbies.concat(this.state.userInput);
this.setState({ hobbies: hobby, userInput: '' }, () =>
updateHobbies(this.state.hobbies));
};
handleDelete = e => {
const array = [...this.state.hobbies];
const index = array.indexOf(e);
if (index !== -1) {
array.splice(index, 1);
this.setState({ hobbies: array }, () =>
updateHobbies(this.state.hobbies));
}
};
render() {
return (
<div>
<label className='employee-label'>HOBBIES: </label>
<span>
<input type='text' value={this.state.userInput} onChange=
{this.handleChange} />
<button className='update-details-button' onClick=
{this.handleButtonClick}>
Add
</button>
{this.state.hobbies.map(hobbies => {
return (
<li className='employee-tag-list' key={hobbies}>
{hobbies}
<span className='delete-icons' onClick={() =>
this.handleDelete(hobbies)}>
<MdDelete />
</span>
</li>
);
})}
</span>
</div>
);
}
}
EditProfile.propTypes = {
employeeHobbies: PropTypes.array
};
export default EditProfile;
EditProfile.test.js
let component;
const chance = new Chance();
let mockHandleChange = jest.fn();
let mockHandleButtonClick = jest.fn();
let mockHandleDelete = jest.fn();
let mockUpdateHobbies;
let mockHobbies = [chance.string(), chance.string(), chance.string()];
function requiredProps(overrides = {}) {
return {
handleChange: mockHandleChange,
handleButtonClick: mockHandleButtonClick,
handleDelete: mockHandleDelete,
...overrides
};
}
function renderComponent(props = requiredProps()) {
return shallow(<Hobbies {...props} />);
}
beforeEach(() => {
component = renderComponent();
});
it('should exist', () => {
console.log(component.debug());
expect(component).toHaveLength(1);
});
I expected the test to pass but I am getting the error, TypeError: Cannot read property 'map' of undefined
There are a few things that you can do, that all aim to solve the core problem: you are not supplying a value for the employeeHobbies prop in your test.
Pick one of the following:
As #Hoyen suggested, add default props to specify an empty array for employeeHobbies if it isn't supplied. EditProfile.defaultProps = { employeeHobbies: [] };.
In your requiredProps() function in your test file, specify a value for employeeHobbies of an empty array along with your other properties like handleChange, handleButtonClick, etc.
When initializing state.employeeHobbies, set it to this.props.employeeHobbies || [], so it has a fallback value if passed null or nothing (undefined).
I also recommend you specify the proptype for employeeHobbies as PropTypes.array.isRequired to get a helpful warning when the array isn't supplied. That will guard against misuse of the component, and violating the contract it needs to work.

Jest TypeError: e.preventDefault is not a function

I'm trying to test the onSubmit method, however im getting this error.
TypeError: e.preventDefault is not a function
I'm referencing this blog tutorial
https://medium.com/#aghh1504/6-testing-react-components-using-jest-and-enzyme-b85db96fa1e3
i referenced another question but no answer
e.preventDefault is not a function - Jest React
App.test.tsx
describe('Should test onSubmit method',() => {
it('should test onSubmit method', ()=>{
const component = shallow(<App/>)
const preventDefault = jest.fn();
const items = ['Learn react', 'rest', 'go out'];
component.setState({
currentTask:"test-task",
tasks:[...items, 'test-task']
})
component.find('form').simulate('submit', preventDefault);
expect(preventDefault).toBeCalled();
})
})
App.tsx
import React from 'react';
import logo from './logo.svg';
import './App.css';
// we need an interface to be able to use the state properties, if not error.
// the same rule applies when using props
// so here we call Istate
interface IState {
currentTask: string;
tasks: Array<string>;
}
export default class App extends React.Component<{}, IState>{
constructor(props: {}){
super(props);
this.state = {
currentTask: "",
tasks:[]
}
}
// when using e.preventDefault in typescript, or any paramater, it has to be followed
// by the following any, array, string, etc. in this case we use any
handleSubmit(e: any){
e.preventDefault();
this.setState({
currentTask: "",
tasks: [...this.state.tasks, this.state.currentTask]
}, () => {
console.log(this.state.tasks)
})
}
onChange = (e: any) => {
e.preventDefault();
this.setState({
currentTask: e.target.value
})
}
render(){
return (
<div className="App">
<h1 className="sampleh1">React Typescript Todo</h1>
<form onSubmit={(e) => this.handleSubmit(e)}>
<input value={this.state.currentTask} type="text" placeholder="enter a todo"
onChange={this.onChange}/>
<button type="submit"> Add Todo</button>
</form>
</div>
);
}
}
Try passing mockEvent object as second argument.
component.find('form').simulate('submit', { preventDefault });
If you using Jest
form.simulate(`submit`, {preventDefault: jest.fn()});
or just an empty function if you don't
form.simulate(`submit`, {preventDefault: () => {}});
The second argument to simulate is the mock event that gets passed to the handler when you call onSubmit, so it has to be in the form of the event object that handler expects:
component.find('form').simulate('submit', { preventDefault });
Likewise, if you're going to test your onChange function, you'll need to pass a mock event with a target/value as the 2nd argument to simulate:
component.find('input').simulate('change', { target: { value: 'todo' } });

Testing onChange function in Jest

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);

Resources