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} >
I have a react component consist of my another component and I am using enzyme to test it. Here is my child component rendered in in parent component:
render() {
let returnVal = "";
returnVal = <SpinLoader/>
return (
returnVal
)
}
So for testing I have:
describe("confirmEmail component unit tests", () => {
before(() => {
confirmEmail = shallow(<ConfirmEmail {...props}/>);
});
// this tests that the Login exists and is not empty
describe("confirmEmail component exists", () => {
it("should not be empty", () => {
expect(confirmEmail).to.not.be.empty;
});
});
})
})
the above emptiness test fail since it is not able to recoginze spinloader however if I replace spinloader with a div then it will pass.
Any idea?
** Update:
As soon as I change the returnVal to
returnVal = <div><SpinLoader/></div>
it works.
so the problem is SpinLoader component which is not a standard element and it is my made component
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
I have a component that has a child component.
This child component has some rules to display its children content, and I want to mock it to display the content regardless its rules.
import MediaQuery from './component.media.query'
class Dumb extends Component { render() {
return (
<Fragment>
<div>Generic content</div>
<MediaQuery device="DESKTOP">
<div id="desktop">Specific desktop content</div>
</MediaQuery>
</Fragment>
) } }
I've tried some ways, and even the simplest is not working:
describe('Dumb component', () => {
jest.doMock('./component.media.query', () => {
const Comp = () => <div id='desktop'>Mocked</div>
return Comp
})
it('should display the desktop', () => {
const wrapper = mount(<Dumb />)
expect(wrapper.find('#desktop')).toExist()
})
})
Any ideas?
In your test you can mock it like this :
jest.mock('./component.media.query', () => () => 'MediaQuery')
//note that you have to enter the path relative to the test file.
With enzyme you can find the element like this
wrapper.find('MediaQuery')
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();