0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.