Subhajit Naskar
Subhajit Naskar

Reputation: 1

How to test a method which is resolving a promise and then changing state in React?

I need to test that when button is clicked and after promise resolve state.message === 'loggedIn successfully'

class Login extends Component {

    constructor() {
        this.onLoginClick = this.onLoginClick.bind(this); 
    }

    fetchLogin() {
        return new Promise(function (resolve) {
            reollve({ success: true });
        })
    }

    onLoginClick() {
        let that = this;
        fetchLogin().then(function ({ success }) {
            success ?
                that.setState({ message: 'loggedIn successfully' }) :
                that.setState({ message: 'Fail' });

        })
    }

    render() {
        return (<div>
            <button onClick={this.onLoginClick}></button>
        </div>)
    }
}

Upvotes: 0

Views: 785

Answers (2)

Iva
Iva

Reputation: 16

Since you are performing a test on a promise, you should wait for the function triggered by the button to execute before you can make the assertion (thus the await). The code below should work for you case:

it('should change state on successful login', async () => {
    const wrapper = mount(<Login  />);

    await wrapper.find('button').simulate('click');

    expect(wrapper.state().message).toEqual("loggedIn successfully");
  });

Upvotes: 0

Fabien Greard
Fabien Greard

Reputation: 1894

I guess you are aware of jest simulate in order to simulate your click ( if not then simulate)

You should be able to use jest async/await or promises with jest, here is the link to the official doc

It should be something like this :

it('works with async/await and resolves', async () => {
  const wrapper = mount(<Login />);

  wrapper.find('button').simulate('click'); 

  await expect(wrapper.state().message).resolves.toEqual('loggedIn successfully');
});

Upvotes: 1

Related Questions