I am getting error on using toHaveBeenCalled() in jest? - reactjs

I am getting error on using toHaveBeenCalled, Please correct me where am going wrong
code:
jsx
<item
onClick={ load ? undefined : onClick}
>
test
test('render', () => {
const MockItems = jest.fn()
const prop = {
onClick: MockItems,
}
const onclickProp= output.find(item).props().onClick
onclickProp(undefined)
expect(props.onClick).toHaveBeenCalled()//error
}
error
expect(props.onClick).toHaveBeenCalled()
Warning: An update to null inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */

If the item is inside any other component as a child component you need to dive() on the wrapper component. Shallow rendering gives you access to only outer/parent component layout.
describe('item parent Component', () => {
let wrapper,instance
beforeEach(() => {
mockProps = {
handleClick: jest.fn()
}
const component = (<parent {...mockProps} />)
wrapper = shallow(component).dive()
})
it('item is clicked', () => {
wrapper.find(item).simulate('click')
expect(handleClick).toHaveBeenCalled()
})
)}
<item onClick={ load ? undefined : onClick} >

Related

Why is JEST testing giving "Could not find "store" error when call setState?

I'm trying to test this:
(I need to confirm that when selectedDevice is called with DESKTOP prop, it calls openModal and that method sets the state of modalOpen to true)
openModal = () => {
this.setState({ modalOpen: true });
};
selectedDevice = () => {
const { device } = this.props;
const isMobile = device === MOBILE;
if (isMobile) {
this.closeWindow();
} else {
this.openModal();
}
};
and I'm testing like this (with JEST)
test('should openModal be called', () => {
const wrapper = mount(<Component
{...sampleProps}
deviceType={DESKTOP}
/>);
const selectedDevice = jest.spyOn(wrapper.instance(), 'selectedDevice');
selectedDevice();
expect(wrapper.state().modalActivated).toEqual(true);
});
Apparently, it seems to be reaching the openModal method in my component. However, I'm getting this error:
Invariant Violation: Could not find "store" in either the context or props of "Connect(Styled(Component))". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(Styled(Component))".
36 |
37 | openModal = () => {
> 38 | this.setState({ modalOpen: true });
| ^
I saw another solutions to that error message, but nothing seems to work for this specific error.
I already tried wrapping the component inside a Provider component with no luck.
You're getting the error because you're using a component which is wrapped inside of the connect HOC from react-redux and the connect HOC needs the redux Provider component with a state.
Your code should be something like this:
test("should openModal be called", () => {
const wrapper = mount(
<Provider store={CreateANewStoreForTest}>
<Component {...sampleProps} deviceType={DESKTOP} />
</Provider>
);
const selectedDevice = jest.spyOn(wrapper.instance(), "selectedDevice");
selectedDevice();
expect(wrapper.state().modalActivated).toEqual(true);
});
and for data on how to create a store read the DOC here

Using enzyme, How to find a child component in a component react if they are result of function return

I'm using jest/enzyme and want to check existence child elements of React component
if i have function as component child
const children = () => (
<>
<div>...</div>
<div>...</div>
</>
)
return <Component>{children}</Component>;
why i can't do like this
test('Should render div', () => {
wrapper = shallow(<MyComponent />);
const component = wrapper.find(Component);
expect(component.exists()).toBe(true); //return true
const children = wrapper.find('div')
expect(children.exists()).toBe(false); //return false
});
Your children function is basically a render prop and shallow doesn't render it. You can however trigger the rendering by calling it as a function like
shallow(
shallow(<MyComponent />)
.find(Component)
.prop('children')()
)
So your test will look like
test('Should render div', () => {
wrapper = shallow(<MyComponent />);
const component = wrapper.find(Component);
expect(component.exists()).toBe(true); //return true
const renderProp = shallow(component.prop('children')());
const children = renderProp.find('div');
expect(children.exists()).toBe(true);
});

How to set a property on a child component with React-Enzyme

Given the following simple components:
function ValueInput(props) {
const [val, setVal] = useState(props.value);
function onChange (val) {
setVal(val);
props.onValueChanged(val);
}
return <input value={val} onChange={onChange}/>;
}
function MyComponent(props) {
const [val, setVal] = useState(props.value);
function onValueChanged (val) {
setVal(val);
}
return (
<div>
<div>{val}</div>
<ValueInput value={val} onValueChanged={onValueChanged}/>
</div>
);
}
I'm mounting them in order to test them with Enzyme and Jest:
const component = mount(<MyComponent value={42}/>);
const inputEl = component.find('input');
How do change the value of the inner component in order to that any change to ValueInput is reflected on MyComponent? I'm trying with the following code, but it doesn't work:
console.log(component.debug());
valueInputEl.setProps({value: 24});
// component.update();
console.log(component.debug());
And I get the following error:
ReactWrapper::setProps() can only be called on the root
You could shallow mount your MyComponent and then test it by triggering the onValueChanged prop of your ValueInput child component and test the changes in your state by checking the value prop of the child component.
test('That the parent element is changed when the child component is changed', () => {
const component = shallow(<MyComponent value={42} />);
component.find(ValueInput).prop('onValueChanged')(24);
expect(component.find(ValueInput).prop('value')).toBe(24);
console.log(component.debug());
});
And test for the behaviour of the ValueInput's onChange methods in its own component tests so that it acts more like a unit test.

How to test or get value from state in react?

Hi could you please tell me How to test or get value from state in react ?
getting error
wrapper.instance(...).handleClickShowPassword is not a function
here is my code
https://codesandbox.io/s/l2lk4n794l
it("toggle showpassword value", () => {
wrapper.setState({ showPassword: false });
wrapper.instance().handleClickShowPassword();
expect(wrapper.state.showPassword).toEqual(true);
});
Since LoginContainer is an wrapped with an HOC, you either need to export the component without withStyles HOC or use dive on the wrapper to get the instance of the component. Also state is a function on component instance and hence you need to call it to access state
describe("<LoginContainer/>", () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<LoginContainer />);
});
it("toggle showpassword value", () => {
const comp = wrapper.dive();
comp.dive().setState({ showPassword: false });
comp.instance().handleClickShowPassword();
expect(comp.state("showPassword")).toEqual(true);
});
});
Working demo

Testing input.focus() in Enzyme

How do I test input.focus() in enzyme. I am writing the script with react. My code is below:
public inputBox: any;
componentDidUpdate = () => {
setTimeout(() => {
this.inputBox.focus();
}, 200);
}
render() {
return (
<div>
<input
type = 'number'
ref = {element => this.inputBox = element } />
</div>
);
}
You can use mount instead of shallow.
Then you can compare document.activeElement and the input DOM node for equality.
const output = mount(<MyFocusingComponent/>);
assert(output.find('input').node === document.activeElement);
See https://github.com/airbnb/enzyme/issues/316 for more details.
Per React 16.3 updates... using createRef for anyone visiting this post today, if you rearrange the original component to use the new ref api
class InputBox extends PureComponent {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
this.inputRef.current.focus();
}
render() {
return (
<input
ref={this.inputRef}
/>
);
}
}
Then in your test spec
it("Gives immediate focus on to name field on load", () => {
const wrapper = mount(<InputBox />);
const { inputRef } = wrapper.instance();
jest.spyOn(inputRef.current, "focus");
wrapper.instance().componentDidMount();
expect(inputRef.current.focus).toHaveBeenCalledTimes(1);
});
Notice the use of the inputRef.current attribute which references the currently assigned DOM node.
Other approach is to test if element gains focus, i.e. focus() is called on node element. To achieve this, focused element need to be referenced via ref tag like it takes place in your example – reference was assigned to this.inputBox. Consider example below:
const wrapper = mount(<FocusingInput />);
const element = wrapper.instance().inputBox; // This is your input ref
spyOn(element, 'focus');
wrapper.simulate('mouseEnter', eventStub());
setTimeout(() => expect(element.focus).toHaveBeenCalled(), 250);
This example uses Jasmine's spyOn, though you can use any spy you like.
I just had the same issue and solved using the following approach:
My setup is Jest (react-create-app) + Enzyme:
it('should set the focus after render', () => {
// If you don't create this element you can not access the
// document.activeElement or simply returns <body/>
document.body.innerHTML = '<div></div>'
// You have to tell Enzyme to attach the component to this
// newly created element
wrapper = mount(<MyTextFieldComponent />, {
attachTo: document.getElementsByName('div')[0]
})
// In my case was easy to compare using id
// than using the whole element
expect(wrapper.find('input').props().id).toEqual(
document.activeElement.id
)
})
This worked for me when using mount and useRef hook:
expect(wrapper.find('input').get(0).ref.current).toEqual(document.activeElement)
Focus on the particular element can be checked using selectors.
const wrapper = mount(<MyComponent />);
const input = wrapper.find('input');
expect(input.is(':focus')).toBe(true);
Selecting by data-test attribute or something similar was the most straight forward solution I could come up with.
import React, { Component } from 'react'
import { mount } from 'enzyme'
class MyComponent extends Component {
componentDidMount() {
if (this.inputRef) {
this.inputRef.focus()
}
}
render() {
return (
<input data-test="my-data-test" ref={input => { this.inputRef = input } } />
)
}
}
it('should set focus on mount', () => {
mount(<MyComponent />)
expect(document.activeElement.dataset.test).toBe('my-data-test')
})
This should work
const wrapper = mount(<MyComponent />);
const input = wrapper.find('input');
expect(input).toHaveFocus();

Resources