I have a class-based component that has the following method:
componentDidUpdate(prevProps) {
if (prevProps.location.pathname !== this.props.location.pathname) {
this.props.onDelete();
}
}
I have the following test that is failing:
it(`should call the 'onDelete' function when 'location.pathName' prop changes`, () => {
const wrapper = mount(<AlertsList.WrappedComponent {...props} />);
// test that the deleteFunction wasn't called yet
expect(deleteFunction).not.toHaveBeenCalled();
// now update the prop
wrapper.setProps({ location: { ...props.location, pathName: "/otherpath" } });
// now check that the deleteFunction was called
expect(deleteFunction).toHaveBeenCalled();
});
where props is initialized in a beforeEach statement like so:
beforeEach(() => {
props = {
...
location: { pathName: "/" }
};
});
But my test fails in the second case after the setProps is called, where I would expect the lifecycle method to have run. What am I doing wrong here?
Issue was a typo, see comments under my original post.
Related
I have a function that should get invoked when a prop (newItems) changes:
componentDidUpdate(prevProps) {
const { title } = this.state;
const { newItems } = this.props;
const { newItems: prevNewItems } = prevProps;
if (prevNewItems !== newItems) {
this.updateTitle(title, newItems); // testing if this method gets called
}
}
The problem on the test below is that componentDidUpdate lifecycle hook doesn't register a new prop after I call setProps, thus the spy receives "0 number of calls"
it('calls updateTitle when newItems changes', () => {
const wrapper = mount(
<Provider store={store}>
<MyComponent {...props} newItems={0}/>
</Provider>,
);
const MyComponentWrapper = wrapper.find('MyComponent');
const spy = jest.spyOn(MyComponentWrapper.instance(), 'updateTitle');
wrapper.setProps({
children: <MyComponent {...props} newItems={1} />
});
wrapper.update();
expect(spy).toHaveBeenCalled(); // Received number of calls: 0 (should be 1)
});
How can I update props on a child component (MyComponent) that is wrapped in a Provider?
You can update the props of the child component (MyComponent) by passing new props to the wrapper.setProps() method. Instead of passing children property, pass the updated newItems property:
wrapper.setProps({
newItems: 1
});
You can then call wrapper.update() to re-render the component with the updated props.
After this, the componentDidUpdate lifecycle method should be triggered, and the updateTitle method should be called with the updated newItems prop.
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} >
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 loads another component, sending it an anonymous function as a prop:
export class Header extends Component {
constructor(props) {
super(props)
this.state = { activeTab: TAB_NAMES.NEEDS_REVIEW }
}
filterByNeedsReview() {
const { filterByNeedsReviewFn } = this.props
this.setState({ activeTab: TAB_NAMES.NEEDS_REVIEW })
filterByNeedsReviewFn()
}
...
render() {
return (
<Container>
...
...
<FilterTab
active={this.state.activeTab === TAB_NAMES.NEEDS_REVIEW}
name={TAB_NAMES.NEEDS_REVIEW}
count={40}
onClick={() => this.filterByNeedsReview()}
/>
...
...
</Container>
)
}
}
I have this failing test:
it('renders a filter tab with the right props for needs review', () => {
const filterByNeedsReviewFn = jest.fn()
expect(
shallowRender({ filterByNeedsReviewFn })
.find(FilterTab)
.findWhere(node =>
_.isMatch(node.props(), {
active: true,
name: 'Needs Review',
count: 40,
onClick: filterByNeedsReviewFn, //<-------------- THIS DOESN'T WORK
})
)
).toHaveLength(1)
})
How would I test that onClick is the right thing?
I believe you don't need to check how internal event handlers look like. You might be interested in different things: if triggering event handler changes component as you expect(.toMatchSnapshot() is much better here instead of testing structure manually with .toHaveLength) and if callback you've passed through props is called when it should to(.toHaveBeenCalled). What if component is changed some day not to just call .props.filterByNeedsReviewFn() but also do some stuff like calling anything else? should your test fail just because there is named method passed somewhere inside? I believe it is not.
So I see your test to be
it('renders a filter tab with expected props after clicking', () => {
const comp = shallowRender({});
comp.find(FilterTab).simulate('click');
expect(comp).toMatchSnapshot();
});
it('calls callback passed after clicking on filter tab', () => {
const filterByNeedsReviewFn = jest.fn()
const comp = shallowRender({ filterByNeedsReviewFn });
comp.find(FilterTab).simulate('click');
// let's ensure callback has been called without any unexpected arguments
expect(filterByNeedsReviewFn ).toHaveBeenCalledWith();
});
I don't think you actually needed this code but I wanted to illustrate how clear such approach could be. Your component have API: props callback it calls and render output. So we can skip testing internals without any pitfalls
My component has:
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm:
typeof this.props.match.params.searchTerm !== "undefined"
? this.props.match.params.searchTerm
: ""
};
}
and the test is:
test("Search should render correct amount of shows", () => {
const component = shallow(<Search shows={preload.shows} />);
expect(component.find(ShowCard).length).toEqual(preload.shows.length);
});
I get
TypeError: Cannot read property 'params' of undefined
How can I fix that or how to set query params in my test?
It seems like when outside the test, the Search component receives the match props correctly.
You could pass it as props when shallow rendering it in the test:
test("Search should render correct amount of shows", () => {
const match = { params: { searchTerm: 'foo' } }
const component = shallow(<Search shows={preload.shows} match={match}/>);
expect(component.find(ShowCard).length).toEqual(preload.shows.length);
});
And in that case, you're not changing the component under test in a bad way, your test case just found a bug, which is good and should be aimed in tests, and you improved the component by implementing a default props, making it more robust.
you should defined a location first in your it/test.
it('App init', async () => {
const location = {
...window.location,
search: '?scope=3&elementId=25924',
};
Object.defineProperty(window, 'location', {
writable: true,
value: location,
})
……
})
I also faced same issue and solved by adding a match prop in the component when you pass it in shallow or mount method. Here is the code:
test("Add param in component", () => {
const match = {params : { id: 1 } };
const component = shallow(<YourComponent match={match} />);
expect(/*Write your code here */);
});
As you can see I and having a param as id, replace with whatever is your's.