Jest Enzyme how to shallow test for existence of wrapped component - javascript

I am testing a component that conditionally renders a wrapped component. I am using enzyme and jest and the root component is rendered through the shallow() method.
The issue is testing if the Root component contains the wrapped component.
How would I test if the wrapped component exists without using the mount() render method?
hoc.component.jsx
export function HOC(Component) {
render() {
return <Component />
}
}
wrapped.component.jsx
class WrappedComponent extends React.Component {
...
}
export default HOC(WrappedComponent)
root.component.jsx
class RootComponent extends React.Component {
render() {
return (
condition ? ... :
<WrappedComponent/>
)
}
}
When testing the root.component.jsx I would like to check if the WrappedComponent exists.
root.component.spec.js
import { WrappedComponent } from 'WrappedComponent'
const wrapper = shallow(<RootComponent {...props}/>);
wrapper.find(WrappedComponent).length => returns 0
If I log wrapper.debug() I see the following:
...<HOC(WrappedComponent) />
How would I test the existence of the WrappedComponent while testing the RootComponent?

It should be possible to assert the existence of a component, as long as WrappedComponent in tests is not original component class but a component wrapped in HOC, i.e. HOC(WrappedComponent).
If HOC(WrappedComponent) is default export, it should be:
import WrappedComponent from 'WrappedComponent'
...
const wrapper = shallow(<RootComponent {...props}/>);
expect(wrapper.find(WrappedComponent).length).toBe(1);

You can use the selector 'HOC(WrappedComponent)':
test('WrappedComponent is rendered', () => {
const wrapper = shallow(<RootComponent {...props}/>);
expect(wrapper.find('HOC(WrappedComponent)').length).toEqual(1);
}

Related

Spreading props in React Higher Order Components

I am trying to go very in-depth to understand the purpose of spreading props in React HOC
So taking the below example;
const EnhanceComponent = BaseComponent => {
return class EnhancedComponent extends Component {
state = {
name: 'You have been enhanced'
}
render() {
return (
<BaseComponent {...this.props} {...this.state} />
)
}
}
};
export default EnhanceComponent;
Now let's say the usage of BaseComponent is as below;
<BaseComponent className='wrapper-container' onClick={this.handleClick} />
I assume if had not spread the props in the HOC, we would have been unable to access "this.props.className" OR "this.props.onClick" in BaseComponent. Would that be correct understanding ?
class BaseComponent extends React.Component {
render() {
const { className, onClick} = this.props;
...
}
}
Now to use the HOC itself, we would say;
const EnhancedMyComponent = EnhanceComponent(MyComponent);
And render it as
<EnhancedMyComponent className='wrapper-container' onClick={this.handleClick} />
Now, below are my 2 specific questions;
What do we finally render i.e. BaseComponent or EnhancedMyComponent OR using HOC allows us to use either flavor e.g. in some case, if we do not want the enhanced functionality, we just use the base component ?
OR
<EnhancedMyComponent className='wrapper-container' onClick={this.handleClick} />
Would the props access issue i.e. if we do not spread the props be applicable in both the above cases of consumption i.e. <BaseComponent /> AND <EnhancedMyComponent /> ?
1) What do we finally render i.e. BaseComponent or EnhancedMyComponent OR using HOC allows us to use either flavor e.g. in some case, if we do not want the enhanced functionality, we just use the base component ?
/ Using HOC allows us to use either flavor. It totally depends where we are wrapping the Component in HOC i.e while exporting or while using it at someplace.
Now, In the below case one has the option to use it with or without HOC
// BaseComponent.js
class BaseComponent extends React.Component {
render() {
const { className, onClick} = this.props;
...
}
}
export default BaseComponent;
// SomeComponent.js
import BaseComponent from './BaseComponent';
const MyComponent = EnhanceComponent(BaseComponent);
class SomeComponent extends React.Component {
render() {
return (
...
<MyComponent className={...} onClick={...} someExtraPropForHOC={...}/>
<BaseComponent className={...} onClick={...} />
...
)
}
To not allow anyone to directly use the Component, wrap it in HOC and export
// BaseComponent.js
class BaseComponent extends React.Component {
render() {
const { className, onClick} = this.props;
...
}
}
export default EnhanceComponent(BaseComponent);
// SomeComponent.js
import BaseComponent from './BaseComponent';
class SomeComponent extends React.Component {
render() {
return (
...
<BaseComponent className={...} onClick={...}/>
...
)
}
2) Would the props access issue i.e. if we do not spread the props be applicable in both the above cases of consumption i.e. AND ?
/ Spread the props is needed as HOC does not know what props would be needed for the dynamically wrapped component. So pass all the props which are coming is the only possible way.
class BaseComponent extends React.Component {
render() {
const { className, onClick} = this.props;
...
}
}
class CustomTextField extends React.Component {
render() {
const { className, onKeyPress, value} = this.props;
...
}
}
const EnhancedBaseComponent = EnhanceComponent(BaseComponent);
const EnhancedTextComponent = EnhanceComponent(CustomTextField);
Now in this case EnhancedBaseComponent and EnhancedTextComponent both need different props, but since they are wrapped in EnhanceComponent. It won't know which props to pass. So spread it and send all the props coming to it.

Jest expected mock not called (redux component)

In React, I am testing that a button click inside a child component causes a function to be called in the parent component (onDeleteClick), via event bubbling.
For this test, I am using mount, as shallow will not allow us to trigger a function in a child component.
onDeleteClick, the function I am trying to check whether it was called or not, is a class property which in this case, is an arrow function.
I am mocking the onDeleteClick function, and passing it into my component via a Redux Provider when starting the test.
The problem I am having is that at the end of the test, when I perform a check to see if the mocked function was called, it returns 0.
expect(onDeleteClick.mock.calls.length).toBe(1);
If I put a console.log within onDeleteClick(), it's outputted during the test, so I know that the function is in fact being called.
I have researched this quite a bit and so far haven't gotten anything to work.
Some suggestions were to spy on my mocked function, and then call forceUpdate on the wrapper, but this didn't yield any positive results.
For this, I am using Jest with Enzyme.
Reference Code:
Parent.js
import { deleteAccount } from '../../actions/profileActions';
import ChildComponent from '../common/ChildComponent';
class ParentComponent extends Component {
onDeleteClick = () => {
console.log('onDeleteClick was executed during this test!')
this.props.deleteAccount();
}
render() {
let dashboardContent;
dashboardContent = (
<div>
<ChildComponent onDelete={this.onDeleteClick} />
</div>
);
return (
<div>
{dashboardContent}
</div>
);
}
}
// propTypes and mapStateToProps removed from this post
export default connect(
mapStateToProps,
{ deleteAccount }
)(ParentComponent);
__tests__/ParentComponent.js
import React from 'react';
import { mount } from 'enzyme';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import ParentComponent from '../ParentComponent';
import thunk from "redux-thunk";
const mockStore = configureStore([thunk]);
const deleteAccount = jest.fn();
const props = {
deleteAccount
}
const randomTestState = {
// some initial state, not important
};
const randomTestStore = mockStore(randomTestState);
describe('<ParentComponent />', () => {
it(`mounts the ParentComponent component and, when ChildComponent sends onDelete, then deleteAccount function is called once`, () => {
const wrapper = mount(
<Provider store={randomTestStore} props={props}>
<Router >
<ParentComponent />
</Router>
</Provider>
);
// Here, I grab an element in ChildComponent and simulate a click using Enzyme, then the event bubbles up, and deleteAccount() is called in the parent component.
// the console.log we expect to see from onDeleteClick is logged to console.
// the call does not seem to have registered though and the expect returns falsy
expect(deleteAccount.mock.calls.length).toBe(1);
})
});
Could the problem be that I am wrapping the component in a Provider?
I have a hunch, but I couldn't find any concrete examples of tests which use a Provider to wrap their component when running integration testing
The solution was that I needed to change my main ParentComponent file from
class ParentComponent extends Component {
to this:
extend class ParentComponent extends Component {
and then in my test file, import the component like so:
import { ParentComponent } from '../ParentComponent'; // non-default export should be wrapped in braces
and then update my test so that I assign the wrapper variable like so:
const wrapper = mount(<ParentComponent {...props} />);
This then allowed the test to pass
expect(deleteAccount.mock.calls.length).toBe(1);
It was recommended here in the Redux docs

Use ref in Higher Order Components

I have a Table component that I want ref to be attached to.
Use: Table.js
class Table extends React.Component {
constructor(props) {
super(props);
this.state = {
rows: 1,
dataLength: props.dataLength,
}
this.tableRef = React.createRef();
}
componentDidUpdate() {
//using ref
this.tableRef.current ..... //logic using ref
this.state.rows ..... //some logic
}
render() {
<TableContainer ref={this.tableRef} />
<CustomPagination />
}
}
This works fine, but now my requirement has changed, and I want to reuse the Table component with pagination applied to all the Tables in my App. I have decided to make a HOC withCustomPagination.
Use: withCustomPagination.js HOC
import CustomPagination from 'path/to/file';
const withCustomPagination = tableRef => Component => {
return class WithCustomPagination extends React.Component {
constructor(props) {
super(props);
this.state = {
rows: 1,
dataLength: props.dataLength,
}
}
componentDidUpdate() {
tableRef.current.state ..... //logic using ref, Error for this line
this.state.rows ..... //some logic
}
render() {
return (
<Component {...state} />
<CustomPagination />
)
}
}
}
export default withCustomPagination;
New Table.js:
import withCustomPagination from '/path/to/file';
const ref = React.createRef();
const Table = props => (
<TableContainer ref={ref} />
);
const WrappedTable = withCustomPagination(ref)(Table);
HOC withCustomPagination returns a class WithCustomPagination that has a componentDidUpdate lifecycle method that uses Table ref in the logic. So I try to pass ref created in Table.js as argument to withCustomPagination, i.e curried with ref and Table stateless component.
This use of ref is wrong and I get error: TypeError: Cannot read property 'state' of null.
I tried using Forwarding Refs, but was unable to implement it.
How do I pass the Table ref to withCustomPagination and be able to use it in HOC?
In this case you can use useImperativeHandle
It means you have to forward ref and specify which function or object or,...
you want to share with ref inside your functional component.
Here is my Hoc example :
import React from 'react';
import { View } from 'react-native';
export function CommonHoc(WrappedComponent) {
const component = class extends React.Component {
componentDidMount() {
this.refs.myComponent.showAlert();
}
render() {
return (
<>
<WrappedComponent
ref='myComponent'
{...this.state}
{...this.props}
/>
</>
);
}
};
return component;
}
and it's my stateless component
const HomeController=(props,ref)=> {
useImperativeHandle(ref, () => ({
showAlert() {
alert("called");
},
}));
return (
<Text>home</Text>
);
};
export default CommonHoc(forwardRef(HomeController));
Either restructure your code to not use a HOC for this or try using React.forwardRef:
Refs Aren’t Passed Through
While the convention for higher-order components is to pass through
all props to the wrapped component, this does not work for refs.
That’s because ref is not really a prop — like key, it’s handled
specially by React. If you add a ref to an element whose component is
the result of a HOC, the ref refers to an instance of the outermost
container component, not the wrapped component.
The solution for this problem is to use the React.forwardRef API
(introduced with React 16.3). Learn more about it in the forwarding
refs section.
via Higher-Order Components: Refs Aren’t Passed Through
In the forwarding refs section there are code examples you could use to pass refs down, but trying to yank them up will fail in your case with:
Warning: Stateless function components cannot be given refs. Attempts to access this ref will fail.
In a project we took a different approach. There's an EnhancedTable component that handles all of the pagination logic and in itself has the dumb table component and the pagination component. It works pretty well but this means you would have to drill props (or use a store lib like Redux or Mobx) and add new ones that will handle pagination options. This will result in some refactoring of Table uses and you'll have to be more explicit but I would take it as a boon rather than a hindrance.
I was able to solve a simmilar issue that brought me to this thread without using forwardRef or useImperativeHandle.
By creating the ref at a higher level, and passign it down into the component and sub components that I needed to act on with the ref.
/** Parent Component has access to ref and functions that act on ref **/
import { useRef } from 'react';
const formRef = useRef(); // ref will have dom elements need accessing
const onClickFunction=()=>{ //sample function acts on ref
var inputs = formRef.current.querySelectorAll('input')
/* Act on ref here via onClick function, etc has access to dom elements
in child component and childs child components */
};
return(
<ComponentGetsAttachedRef formRef={formRef} />
//^ref sent down to component and its children
<ComponentNeedingRef onClickFunction={onClickFunction}/>
//^function with access to ref sent down to component
)
/** Child component needs to act on ref**/
export const ComponentNeedingRef = ({ onClickFunction}) =>{
return(
<button onClick={onClickFunction}>
)
}
/* Child component recieves ref and passes it down */
export const ComponentGetsAttachedRef = ({ formRef}) =>{
//ref comes in as prop gets attached to props or utilized internally
return (
<ChildsChildComponent formRef={formRef}/> //sub component passed ref down
)
}

React propTypes component class?

How can I validate that the supplied prop is a component class (not instance)?
e.g.
export default class TimelineWithPicker extends React.PureComponent {
static propTypes = {
component: PropTypes.any, // <-- how can I validate that this is a component class (or stateless functional component)?
};
render() {
return (
<this.props.component {...this.props} start={this.state.start}/>
);
}
}
For anyone using PropTypes >= 15.7.0 a new PropTypes.elementType was added in this pull request and was released on february 10, 2019.
This prop type supports all components (native components, stateless components, stateful components, forward refs React.forwardRef, context providers/consumers).
And it throws a warning when is not any of those elements, it also throws a warning when the prop passed is an element (PropTypes.element) and not a type.
Finally you can use it like any other prop type:
const propTypes = {
component: PropTypes.elementType,
requiredComponent: PropTypes.elementType.isRequired,
};
EDITED: Added React's FancyButton example to codesandbox as well as a custom prop checking function that works with the new React.forwardRef api in React 16.3. The React.forwardRef api returns an object with a render function. I'm using the following custom prop checker to verify this prop type. - Thanks for Ivan Samovar for noticing this need.
FancyButton: function (props, propName, componentName) {
if(!props[propName] || typeof(props[propName].render) != 'function') {
return new Error(`${propName}.render must be a function!`);
}
}
You'll want to use PropTypes.element. Actually... PropType.func works for both stateless functional components and class components.
I've made a sandbox to prove that this works... Figured this was needed considering I gave you erroneous information at first. Very sorry about that!
Working sandbox example!
Here is the code for the test in case link goes dead:
import React from 'react';
import { render } from 'react-dom';
import PropTypes from "prop-types";
class ClassComponent extends React.Component {
render() {
return <p>I'm a class component</p>
}
}
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
const FSComponent = () => (
<p>I'm a functional stateless component</p>
);
const Test = ({ ClassComponent, FSComponent, FancyButton }) => (
<div>
<ClassComponent />
<FSComponent />
<FancyButton />
</div>
);
Test.propTypes = {
ClassComponent: PropTypes.func.isRequired,
FSComponent: PropTypes.func.isRequired,
FancyButton: function (props, propName, componentName) {
if(!props[propName] || typeof(props[propName].render) != 'function') {
return new Error(`${propName}.render must be a function!`);
}
},
}
render(<Test
ClassComponent={ ClassComponent }
FSComponent={ FSComponent }
FancyButton={ FancyButton } />, document.getElementById('root'));

Unit test: simulate the click event of child component in parent using enzyme

I have a parent component and a child component which is just a "label" element. When i click the child element, i need to call the function in parent component. I expect it to be called but the state doesnt change and when i saw the coverage file the function isnt being called.
**Updated:**The code works for development. It's just the unit test that fails.
Here is my parent component
parent.js
export default class Parent extends Component {
constructor(props) {
super(props)
this.state={clickedChild: false}
this.handleChildClick = this.handleChildClick.bind(this)
}
handleChildClick(index) {
this.setState({clickedChild:true})
}
render(){
const self = this
return(
const items = [{'id':1,'text':'hello'},{'id':2,'text':'world'}]
<div>
{items.map(function(item,index){
return <ChildComponent onChildClick ={ self.handleChildClick.bind(null,index)} childItem={item} />
})}
</div>
)}
}
child component
export default class ChildComponent extends Component {
constructor(props) { super(props)}
render(){
return(
<label onClick={this.props.onChildClick}>{this.props.childItem.text} </label>
)
}
}
unit test
import chai from 'chai'
import React from 'react'
import ReactDOM from 'react-dom'
import { mount, shallow } from 'enzyme';
import sinon from 'sinon'
import Parent from '../Parent'
import ChildComponent from '../ChildComponent'
let expect = chai.expect
describe('check click event on child()',()=>{
it('clicking menu item',()=>{
const items = [{'id':1,'text':'hello'},{'id':2,'text':'world'}]
const wrapper = mount(<Parent items={items} />)
console.log(wrapper.state('clickedChild')) // prints false
wrapper.find(ChildComponent).last().simulate('click',1)
// tried the following
// wrapper.find(ChildComponent).last().simulate('click')
console.log(wrapper.state('clickedChild')) // still prints false
})
})
I changed the binding in my parent component to
<ChildComponent onChildClick ={() => self.handleChildClick(index)} childItem={item} />
There was also a function i was calling in my parent component which was calling its method.(parent.js)
handleChildClick(index) {
this.setState({clickedChild:true})
this.props.handleClick(index) // i had forgotten to see the line.
}
Once i stubbed the above commented line in my test . everything worked as expected.
it('clicking menu item', () => {
const items = [{'id':1,'text':'hello'},{'id':2,'text':'world'}]
const handleClickStub = sinon.spy()
const wrapper = mount(<Parent items={items} handleClick={handleClickStub} />)
console.log(wrapper.state('clickedChild')) // prints false
wrapper.find(ChildComponent).last().simulate('click')
expect(handleClickStub.calledOnce).to.be.true // successful
console.log(wrapper.state('clickedChild')) // prints true
})

Categories

Resources