简体   繁体   中英

React, Jest: simulate submit form unit test

I've stuck with the simple test case and cannot find out the cause it doesn't work. There is the component which I would like to test:

export class SignInForm extends Component {

   onSubmit = (user) => {
       console.log('THERE----', this.props.signin);  // ---> i saw it during testing
       this.props.signin();
   };

   render() {
       return (
           <Form onSubmit={this.onSubmit}>
              {formApi => (
                  <form onSubmit={formApi.submitForm}>
                       <InputFieldGroup field="identifier" label="Username/Email"/>
                       <InputFieldGroup field="password" label="Password" type="password"/>
                       <button type="submit">Submit</button>
                   </form>
               )}
           </Form>
       );
   }

}

and there's my test case.

it('should render in proper way', () => {

    const signinMock = jest.fn();

    const props = {
        signin: signinMock
    };

    const component = mount(<SignInForm {...props}/>);


    component.find('form').simulate('submit');

    console.log(signinMock.mock.calls); // ---> saw empty array []
});

In this case I would expect that signinMock was invoked at once. But I saw the empty array of calls, but during launching test I saw the console log of component method: console.log('THERE----', this.props.signin); and I saw the mock function itself.

console.log executes before the event handlers and hence you see an empty array. The following code would allow the event handlers to execute and then you can do the assertion.

setTimeout(()=> {
    expect(signinMock.mock.calls.length).to.equal(1);
}, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM