Testing state is set correctly in the DidMount component from ajax call

I have the following code in my reaction component

componentDidMount() {

    ajax.call().then((data)=> {

        this.setState({a:data.a});
    });
}

Im making a simple call to a function that returns a promise.

My test looks like this when I try to verify that the state is set correctly from the promises made.

        it('should set state of a', (done)=> {

            let ajax = {
                call: ()=>{}
            };

            spyOn(ajax, 'call').and.returnValue(Promise.resolve({a:'a'}));

            let component = TestUtils.renderIntoDocument(<MyComp/>);

            expect(component.state.a).toEqual('a');
        });

I’m sure that in fact the state is drawn from the data returned by the promise, but the problem is that I can’t call the jasmine function “done ()” to say that the jasmine has completed, the asynchronous operation has completed and that the statement on the state can be checked .

+4
source share
1 answer

React , " " , , . , FLUX , redux este.

, , AJAX, . :

  • state AJAX, , , .
  • render ( setState ing).

, , ( ), AJAX ( ).

, promises mocha, , React, Babel , JavaScript :

it('does ajax', async function(){ // can also `async () =>`
    var result = await ajax.call(); // call the ajax, get response, can be mocked
    var state = result;
    var str = React.renderToString(<MyComp prop={result} />);
    // assert against the returned HTML, can also test against DOM
});
+2

Source: https://habr.com/ru/post/1607034/


All Articles