Reputation: 1039
I want to write unit test for React component's method.
The component's code is
export class LoginForm extends Component {
constructor() {
super();
this.tryLoginProp = this.tryLoginProp.bind(this)
}
render() {
return (
<div className="login-form">
<div className="form-input">
<CustomButton label="Log in"
class="login-button"
action={this.tryLoginProp}
id="login-button-loginform"
renderSpinner={this.props.renderSpinner}
/>
</div>
</div>
)
}
tryLoginProp () {
if (!this.props.renderSpinner) {
this.props.tryLoginProp()
}
}
}
const mapStateToProps = (state) => {
return {
login: state.login,
renderSpinner: state.layout.renderSpinner
};
};
const mapDispatchToProps = (dispatch) => ({
tryLoginProp: () => {
dispatch(tryLogin())
}
});
export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
I want to write unit test for tryLoginProp method, but I am not getting how to mock this.props.tryLoginProp function and pass the test case.
Current unit test is as follows:
describe('<LoginForm />', () => {
const initialState = {renderSpinner: false};
let wrapper;
beforeEach(() => {
wrapper = mount(<LoginForm {...initialState}/>);
});
it('renders without expolding', () => {
expect(wrapper.length).toEqual(1);
});
it('tryLoginProp should dispatch an action', () => {
expect(wrapper.tryLoginProp()). //test tryLoginProp method.
})
});
Please help me to write proper test case for this method.
Thanks
Upvotes: 0
Views: 2548
Reputation: 14927
You can use wrapper.instance().tryLoginProp()
to call the method...like this I think without testing it
it('tryLoginProp should dispatch an action', () => {
const mockedTryLoginProp = jest.fn();
const wrapper = shallow(
<LoginForm
tryLoginProp={mockedTryLoginProp}
renderSpinner={false}
/>
);
wrapper.instance().tryLoginProp();
expect(mockedTryLoginProp).toHaveBeenCalled();
})
On a side note, you may consider naming the internal function differently than the one being passed in to avoid confusion
Upvotes: 1