I have some problems with testing events for nested components.
This is how my component tree look like:
- ModalComponent (Stateful with value for Input and update handler)
- - ModalType (stateless, passes value and update down to input)
- - - Input (stateless)
I have the value state and the handler for updating my value in my ModalComponent. This information just passed down through ModalType to my Input element via props.
I have tried to mount my ModalComponent with enzyme, find my input and simulate a change on the element. But this did not work.
What is the best strategy to test nested component when the handler and state are n parents components above?
EDIT
I have created a lean demo setup of my component in a separate blank react project
class App extends Component {
state = {
inputs: {
machineName: 'Empty'
}
}
onChangeHandler = (e) => {
let updatedState = null
console.log(e.target.value, e.target.id);
switch (e.target.id) {
case 'machineName':
updatedState = { ...this.state.inputs, machineName: e.target.value }
this.setState({inputs: updatedState})
break;
default:
break;
}
}
render() {
return (
<div className="App">
<ModalType onChange={this.onChangeHandler} value={this.state.inputs}></ModalType>
</div>
);
}
}
const ModalType = (props) => {
return <Input onChange={props.onChange} value={props.value.machineName}></Input>
}
const Input = (props) => (
<input id="machineName" onChange={props.onChange} value={props.value}></input>
)
My testing script
test('should handle change on input', () =>{
const wrapper = mount(<App/>)
wrapper.setState({inputs: { machineName: 'Empty' }})
wrapper.find('input').simulate('focus')
wrapper.find('input').simulate('change', {target: {value: '123'}})
wrapper.update()
// fails
expect(wrapper.state().inputs.machineName).toEqual('123')
// fails too
expect(wrapper.find('input').props().value).toEqual('123')
})
Thanks!
const wrapper = mount(<ModalComponent />);
const input = wrapper.find('input');
const event = {target: {value: 'testValue'}};
input.simulate('change', event);
The code above is a working example of how to simulate a change event on your input.
Edit
Your event is not correct. Since your handler is doing something only if the target id is machineName, you need to add that id to your mock event.
wrapper.find('input').simulate('change', {target: {value: '123', id: 'machineName'}})
Related
I'm trying to unit test a very simple feature in a React app where I'm blocking the user from pasting into a textarea by adding an event.preventDefault() in the event handler, like so:
function handlePaste(event) {
event.preventDefault();
}
// ... pass it down as props
<TextareaComponent onPaste={handlePaste} />
The problem I'm having is that every method I've found of dispatching events in Jest or Enzyme just "simulates" the event by getting the function passed to the onPaste prop and calling it directly with a mock event object. That's not what I'm interested in testing.
Ideally I want to do something like this, testing that the actual value of the input hasn't changed after pasting:
const wrapper = mount(<ParentComponent inputValue="Prefilled text" />);
const input = wrapper.find(TextareaComponent);
expect(input.value).toEqual("Prefilled text")
input.doAPaste("Pasted text")
expect(input.value).not.toEqual("Pasted text")
expect(input.value).toEqual("Prefilled text")
But haven't been able to find a method that works. Any help would be appreciated!
Since you're just testing against a synthetic event (and not some sort of secondary action -- like a pop up that warns the user that pasting is disabled), then the easiest and correct solution is to simulate a paste event, pass it a mocked preventDefault function, and then assert that the mocked function was called.
Attempting to make assertions against a real paste event is pointless as this a React/Javascript implementation (for example, making assertions that a callback function is called when an onPaste/onChange event is triggered). Instead, you'll want to test against what happens as a result of calling the callback function (in this example, making assertions that event.preventDefault was called -- if it wasn't called, then we know the callback function was never executed!).
Working example (click the Tests tab to run the assertions):
To keep it simple, I'm just asserting that the input is initially empty and then only updates the value if an onChange event was triggered. This can very easily be adapted to have some sort of passed in prop influence the default input's value.
App.js
import React, { useCallback, useState } from "react";
const App = () => {
const [value, setValue] = useState("");
const handleChange = useCallback(
({ target: { value } }) => setValue(value),
[]
);
const handlePaste = useCallback((e) => {
e.preventDefault();
}, []);
const resetValue = useCallback(() => {
setValue("");
}, []);
const handleSubmit = useCallback(
(e) => {
e.preventDefault();
console.log(`Submitted value: ${value}`);
setValue("");
},
[value]
);
return (
<form onSubmit={handleSubmit}>
<label htmlFor="foo">
<input
id="foo"
type="text"
data-testid="test-input"
value={value}
onPaste={handlePaste}
onChange={handleChange}
/>
</label>
<br />
<button data-testid="reset-button" type="button" onClick={resetValue}>
Reset
</button>
<button type="submit">Submit</button>
</form>
);
};
export default App;
App.test.js
import React from "react";
import { configure, mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import App from "./App";
configure({ adapter: new Adapter() });
const value = "Hello";
describe("App", () => {
let wrapper;
let inputNode;
beforeEach(() => {
wrapper = mount(<App />);
// finding the input node by a 'data-testid'; this is not required, but easier
// when working with multiple form elements and can be easily removed
// when the app is compiled for production
inputNode = () => wrapper.find("[data-testid='test-input']");
});
it("initially displays an empty input", () => {
expect(inputNode()).toHaveLength(1);
expect(inputNode().props().value).toEqual("");
});
it("updates the input's value", () => {
inputNode().simulate("change", { target: { value } });
expect(inputNode().props().value).toEqual(value);
});
it("prevents the input's value from updating from a paste event", () => {
const mockPreventDefault = jest.fn();
const prefilledText = "Goodbye";
// updating input with prefilled text
inputNode().simulate("change", { target: { value: prefilledText } });
// simulating a paste event with a mocked preventDefault
// the target.value isn't required, but included for illustration purposes
inputNode().simulate("paste", {
preventDefault: mockPreventDefault,
target: { value }
});
// asserting that "event.preventDefault" was called
expect(mockPreventDefault).toHaveBeenCalled();
// asserting that the input's value wasn't changed
expect(inputNode().props().value).toEqual(prefilledText);
});
it("resets the input's value", () => {
inputNode().simulate("change", { target: { value } });
wrapper.find("[data-testid='reset-button']").simulate("click");
expect(inputNode().props().value).toEqual("");
});
it("submits the input's value", () => {
inputNode().simulate("change", { target: { value } });
wrapper.find("form").simulate("submit");
expect(inputNode().props().value).toEqual("");
});
});
I am currently converting this open source template (React + Firebase + Material UI). If you look in many parts of the codebase, you'll noticed after a state variable is changed, there will then be a call back. Here is one example from the signUp method found within SignUpDialog.js file:
signUp = () => {
const {
firstName,
lastName,
username,
emailAddress,
emailAddressConfirmation,
password,
passwordConfirmation
} = this.state;
const errors = validate({
firstName: firstName,
lastName: lastName,
username: username,
emailAddress: emailAddress,
emailAddressConfirmation: emailAddressConfirmation,
password: password,
passwordConfirmation: passwordConfirmation
}, {
firstName: constraints.firstName,
lastName: constraints.lastName,
username: constraints.username,
emailAddress: constraints.emailAddress,
emailAddressConfirmation: constraints.emailAddressConfirmation,
password: constraints.password,
passwordConfirmation: constraints.passwordConfirmation
});
if (errors) {
this.setState({
errors: errors
});
} else {
this.setState({
performingAction: true,
errors: null
}, () => { //!HERE IS WHERE I AM CONFUSED
authentication.signUp({
firstName: firstName,
lastName: lastName,
username: username,
emailAddress: emailAddress,
password: password
}).then((value) => {
this.props.dialogProps.onClose();
}).catch((reason) => {
const code = reason.code;
const message = reason.message;
switch (code) {
case 'auth/email-already-in-use':
case 'auth/invalid-email':
case 'auth/operation-not-allowed':
case 'auth/weak-password':
this.props.openSnackbar(message);
return;
default:
this.props.openSnackbar(message);
return;
}
}).finally(() => {
this.setState({
performingAction: false
});
});
});
}
};
With hooks, I tried something like this within the else statement...
setPerformingAction(true)
setErrors(null), () => {...}
I'll be honest, I am not the greatest at callbacks. From what I think this is doing is then calling the following methods after the state has been set. That said, this is not correct according to eslint and I was hoping to see if anyone could help. Thanks, Brennan.
If I understand your question correctly, you would like to know how to achieve the same behavior that the class based setState callback provides, but using functional components..
Thinking in functional components is a different ballgame than thinking in class based components.. The easiest way to put it is that class based components are more imperative, while hooks/functional components are more declarative.
The useEffect hook requires a dependency array (the part at the end }, [clicks]) is the dependency array) - anytime a variable that is included in the dependency array is changed, the useEffect method is fired.
What this means is you can use useEffect in a similar fashion to a setState callback.. Hooks allow you to focus in on, and have fine-grained control over, very specific parts of your state.
This is a good thread to check out - and more specifically, a good explanation of the difference between class based (setState) and hooks based (useState) paradigms.
The following example demonstrates how to achieve something similar to "callback" behavior, but using hooks/functional components.
const { render } = ReactDOM;
const { Component, useState, useEffect } = React;
/**
* Class based with setState
*/
class MyClass extends Component {
state = {
clicks: 0,
message: ""
}
checkClicks = () => {
let m = this.state.clicks >= 5 ? "Button has been clicked at least 5 times!" : "";
this.setState({ message: m });
}
handleIncrease = event => {
this.setState({
clicks: this.state.clicks + 1
}, () => this.checkClicks());
}
handleDecrease = event => {
this.setState({
clicks: this.state.clicks - 1
}, () => this.checkClicks());
}
render() {
const { clicks, message } = this.state;
return(
<div>
<h3>MyClass</h3>
<p>Click 'Increase' 5 times</p>
<button onClick={this.handleIncrease}>Increase</button>
<button onClick={this.handleDecrease}>Decrease</button>
<p><b><i>MyClass clicks:</i></b> {clicks}</p>
<p>{message}</p>
</div>
);
}
}
/**
* Function based with useState and useEffect
*/
function MyFunction() {
const [clicks, setClicks] = useState(0);
const [message, setMessage] = useState("");
useEffect(() => {
let m = clicks >= 5 ? "Button has been clicked at least 5 times!" : "";
setMessage(m);
}, [clicks]);
const handleIncrease = event => setClicks(clicks + 1);
const handleDecrease = event => setClicks(clicks - 1);
return(
<div>
<h3>MyFunction</h3>
<p>Click 'Increase' 5 times</p>
<button onClick={handleIncrease}>Increase</button>
<button onClick={handleDecrease}>Decrease</button>
<p><b><i>MyFunction clicks:</i></b> {clicks}</p>
<p>{message}</p>
</div>
);
}
function App() {
return(
<div>
<MyClass />
<hr />
<MyFunction />
</div>
);
}
render(<App />, document.body);
p {
margin: 1px;
}
h3 {
margin-bottom: 2px;
}
h3 {
margin-top: 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
You can use the setter of useState multiple times in a handler but you should pass a function to the setter instead of just setting it.
This also solves missing dependency if you create your handler with useEffect.
const [state, setState] = useState({ a: 1, b: 2 });
const someHandler = useCallback(
() => {
//using callback method also has the linter
// stop complaining missing state dependency
setState(currentState => ({ ...currentState, a: currentState.a + 1 }));
someAsync.then(result =>
setState(currentState => ({
...currentState,
b: currentState.a * currentState.b,
}))
);
},
//if I would do setState({ ...state, a: state.a + 1 });
// then the next line would need [state] because the function
// has a dependency on the state variable. That would cause
// someHandler to be re created every time state changed
// and can make useCallback quite pointless
[] //state dependency not needed
);
Note that this component can actually be unmounted before your async work finishes and would cause a warning if you call state setter when component is unmounted so you'd better wrap the setter.
Last time I told you that checking mounted is pointless because you were checking it in App component and that component never unmounts (unless you can show me some place in your code that does unmount it) but this component looks like something that may unmount at some point.
In this case if you want to run some callback function if there are any errors after performing an action, you can use useEffect in this case since react hooks do not accept a 2nd optional callback function as with setState.
you can add errors into the dependency array of useEffect and write your callback function inside useEffect. Which will potentionally mean to run some funtion if there are any errors.
performAnAction = () => {
if (actionWentWrong) {
setError(); // maintained in state using useState ( const [error, setError] = useState(false);
}
}
useEffect(() => {
// inside of this function if there are any errors do something
if(error) {
// do something which you were previously doing in callback function
}
}, [error]); // this useEffect is watching if there is any change to this error state
I'm trying to test the onChange prop (and the value) of an input on an RFC. On the tests, trying to simulate the event doesn't fire the jest mock function.
The actual component is connected (with redux) but I'm exporting it also as an unconnected component so I can do a shallow unit test. I'm also using some react-spring hooks for animation.
I've also tried to mount instead of shallow the component but I still get the same problem.
MY Component
export const UnconnectedSearchInput: React.FC<INT.IInputProps> = ({ scrolled, getUserInputRequest }): JSX.Element => {
const [change, setChange] = useState<string>('')
const handleChange = (e: InputVal): void => {
setChange(e.target.value)
}
const handleKeyUp = (): void => {
getUserInputRequest(change)
}
return (
<animated.div
className="search-input"
data-test="component-search-input"
style={animateInputContainer}>
<animated.input
type="text"
name="search"
className="search-input__inp"
data-test="search-input"
style={animateInput}
onChange={handleChange}
onKeyUp={handleKeyUp}
value={change}
/>
</animated.div>
)
}
export default connect(null, { getUserInputRequest })(UnconnectedSearchInput);
My Tests
Here you can see the test that is failing. Commented out code is other things that I-ve tried so far without any luck.
describe('test input and dispatch action', () => {
let changeValueMock
let wrapper
const userInput = 'matrix'
beforeEach(() => {
changeValueMock = jest.fn()
const props = {
handleChange: changeValueMock
}
wrapper = shallow(<UnconnectedSearchInput {...props} />).dive()
// wrapper = mount(<UnconnectedSearchInput {...props} />)
})
test('should update input value', () => {
const input = findByTestAttr(wrapper, 'search-input').dive()
// const component = findByTestAttr(wrapper, 'search-input').last()
expect(input.name()).toBe('input')
expect(changeValueMock).not.toHaveBeenCalled()
input.props().onChange({ target: { value: userInput } }) // not geting called
// input.simulate('change', { target: { value: userInput } })
// used with mount
// act(() => {
// input.props().onChange({ target: { value: userInput } })
// })
// wrapper.update()
expect(changeValueMock).toBeCalledTimes(1)
// expect(input.prop('value')).toBe(userInput);
})
})
Test Error
Nothing too special here.
expect(jest.fn()).toBeCalledTimes(1)
Expected mock function to have been called one time, but it was called zero times.
71 | // wrapper.update()
72 |
> 73 | expect(changeValueMock).toBeCalledTimes(1)
Any help would be greatly appreciated since it's been 2 days now and I cn't figure this out.
you don't have to interact with component internals; instead better use public interface: props and render result
test('should update input value', () => {
expect(findByTestAttr(wrapper, 'search-input').dive().props().value).toEqual('');
findByTestAttr(wrapper, 'search-input').dive().props().onChange({ target: {value: '_test_'} });
expect(findByTestAttr(wrapper, 'search-input').dive().props().value).toEqual('_test_');
}
See you don't need to check if some internal method has been called, what's its name or argument. If you get what you need - and you require to have <input> with some expected value - it does not matter how it happened.
But if function is passed from the outside(through props) you will definitely want to verify if it's called at some expected case
test('should call getUserInputRequest prop on keyUp event', () => {
const getUserInputRequest = jest.fn();
const mockedEvent = { target: { key: 'A' } };
const = wrapper = shallow(<UnconnectedSearchInput getUserInputRequest={getUserInputRequest } />).dive()
findByTestAttr(wrapper, 'search-input').dive().props().onKeyUp(mockedEvent)
expect(getUserInputRequest).toHaveBeenCalledTimes(1);
expect(getUserInputRequest).toHaveBeenCalledWith(mockedEvent);
}
[UPD] seems like caching selector in interm variable like
const input = findByTestAttr(wrapper, 'search-input').dive();
input.props().onChange({ target: {value: '_test_'} });
expect(input.props().value).toEqual('_test_');
does not pass since input refers to stale old object where value does not update.
At enzyme's github I've been answered that it's expected behavior:
This is intended behavior in enzyme v3 - see https://github.com/airbnb/enzyme/blob/master/docs/guides/migration-from-2-to-3.md#calling-props-after-a-state-change.
So yes, exactly - everything must be re-found from the root if anything has changed.
So I am practicing React and wanted to display a "Arya's kill list" ], I wanted to make it possible to update it. So in my ToKill component when you double click on a character it shows inputs with values. But it is not possible to update them.
I wrote a function in my main App component it looks like this :
const toKillPpl = { ...this.state.toKill }
toKillPpl[index] = updatedToKill
this.setState({ toKillPpl })
}
next I pass it to ToKillList component with a state :
doubleClick = {this.doubleClickHandler}
deleteToKill = {this.deleteToKillHandler}
backBtn = {this.backBtnHandler}
state = {this.state}
toKillState = {this.state.toKill}
update = {this.toKillUpdate}
/>
in my ToKillList component I map over my state and I pass this function with a state of a person (toKillPerson) :
const ToKillList = (props) => props.state.toKill.map((toKill, index) => {
return <ToKill
double ={() => props.doubleClick(index)}
formDouble={toKill.formDouble}
click ={() => props.deleteToKill(index)}
backBtn ={() => props.backBtn(index)}
key={index + toKill.name}
index={index}
toKillPerson ={props.toKillState[index]}
update={props.update}
name={toKill.name}
cause={toKill.cause}
img={toKill.img}
/>
})
Finally in my ToKill component I write a function "handleChange" :
handleChange = (e) => {
const updatedToKill = {
...this.props.toKillPerson,
[e.currentTarget.name]: e.currentTarget.value
}
this.props.update(this.props.index, updatedToKill)
}
And here are inputs:
<input
type="text"
name="name"
className="hero-name"
onChange={this.handleChange}
value={this.props.name}
/>
<input
type="text"
name="img"
onChange={this.handleChange}
value={this.props.img}
/>
<input
type="text"
name="cause"
className="hero-cause"
onChange={this.handleChange}
value={this.props.cause}
/>
And it doesn't work. Is it a good approach, or I messed it up completely?
In case I wasn't clear here is a github repo: https://github.com/jakubmas/Aryas-Kill-List
Two correction in update method in your code.
1) You are not correctly copying over object,
const toKillPpl = { ...this.state.toKill }
This creates a shallow copy, you need deep cloning for this. You could either use JSON.strigify or lodash deepClone method.
2) You are not updating toKill state which is being passed to child components.
Here is the updated method:
toKillUpdate = (index, updatedToKill) => {
// const toKillPpl = JSON.parse(JSON.stringify(this.state.toKill)); // use this
const toKillPpl = _.cloneDeep(this.state.toKill); // or this
toKillPpl[index] = updatedToKill;
this.setState({ toKill: toKillPpl });
};
Here is the working codesandbox link
Hope that helps!!!
Another way to do this is that you could import immutability-helper (https://github.com/kolodny/immutability-helper), and use it to update state.toKill without mutating it:
import update from 'immutability-helper';
// Assuming 'updateToKill' input is an object...
handleUpdate = (index, updatedToKill) => {
this.setState(prevState => ({
toKill: update(prevState.toKill, {
[index]: {
$set: updatedToKill,
},
}),
}));
};
I've got an onChange handler on an input that I'm trying to test based on what I've read in the Dom Testing Library docs here and here.
One difference in my code is that rather than using local state to control the input value, I'm using props. So the onChange function is actually calling another function (also received via props), which updates the state which has been "lifted up" to another component. Ultimately, the value for the input is received as a prop by the component and the input value is updated.
I'm mocking the props and trying to do a few simple tests to prove that the onChange handler is working as expected.
I expect that the function being called in the change handler to be called the same number of times that fireEvent.change is used in the test, and this works with:
const { input } = setup();
fireEvent.change(input, { target: { value: "" } });
expect(handleInstantSearchInputChange).toHaveBeenCalledTimes(1);
I expect that the input.value is read from the original mock prop setup, and this works with:
const { input } = setup();
expect(input.value).toBe("bacon");
However, I'm doing something stupid (not understanding mock functions at all, it would seem), and I can't figure out why the following block does not update the input.value, and continues to read the input.value setup from the original mock prop setup.
This fails with expecting "" / received "bacon" <= set in original prop
fireEvent.change(input, { target: { value: "" } });
expect(input.value).toBe("");
QUESTION: How can I write a test to prove that the input.value has been changed given the code below? I assume that I need the mock handleInstantSearchInputChange function to do something, but I don't really know what I'm doing here quite yet.
Thanks for any advice on how to do and/or better understand this.
Test File
import React from "react";
import InstantSearchForm from "../../components/InstantSearchForm";
import { render, cleanup, fireEvent } from "react-testing-library";
afterEach(cleanup);
let handleInstantSearchInputChange, props;
handleInstantSearchInputChange = jest.fn();
props = {
foodSearch: "bacon",
handleInstantSearchInputChange: handleInstantSearchInputChange
};
const setup = () => {
const utils = render(<InstantSearchForm {...props} />);
const input = utils.getByLabelText("food-search-input");
return {
input,
...utils
};
};
it("should render InstantSearchForm correctly with provided foodSearch prop", () => {
const { input } = setup();
expect(input.value).toBe("bacon");
});
it("should handle change", () => {
const { input } = setup();
fireEvent.change(input, { target: { value: "" } });
expect(input.value).toBe("");
fireEvent.change(input, { target: { value: "snickerdoodle" } });
expect(input.value).toBe("snickerdoodle");
});
Component
import React from "react";
import PropTypes from "prop-types";
const InstantSearchForm = props => {
const handleChange = e => {
props.handleInstantSearchInputChange(e.target.value);
};
return (
<div className="form-group">
<label className="col-form-label col-form-label-lg" htmlFor="food-search">
What did you eat, fatty?
</label>
<input
aria-label="food-search-input"
className="form-control form-control-lg"
onChange={handleChange}
placeholder="e.g. i ate bacon and eggs for breakfast with a glass of whole milk."
type="text"
value={props.foodSearch}
/>
</div>
);
};
InstantSearchForm.propTypes = {
foodSearch: PropTypes.string.isRequired,
handleInstantSearchInputChange: PropTypes.func.isRequired
};
export default InstantSearchForm;
The way you are thinking about your tests is slightly incorrect. The behavior of this component is purely the following:
When passed a text as a prop foodSearch renders it correctly.
Component calls the appropriate handler on change.
So only test for the above.
What happens to the foodSearch prop after the change event is triggered is not the responsibility of this component(InstantSearchForm). That responsibility lies with the method that handles that state. So, you would want to test that handler method specifically as a separate test.