Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - React Enzyme - Test `componentDidMount` Async Call

everyone.

I'm having weird issues with testing a state update after an async call happening in componentDidMount.

Here's my component code:

'use strict';


import React from 'react';
import UserComponent from './userComponent';
const request = require('request');


class UsersListComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      usersList: []
    };
  }

  componentDidMount() {
    request('https://api.github.com/users', (err, res) => {
      if (!err && res.statusCode === 200) {
        this.setState({
          usersList: res.slice(0)
        });
      }
      else {
        console.log(err);
      }
    });
  }

  render() {
    if (!this.state.usersList.length) {
      return null;
    }

    return (
      <div className="users-list">
        { this._constructUsersList() }
      </div>
    );
  }

  _constructUsersList() {
    return this.state.usersList.map((user, index) => {
      return (
        <UserComponent
              key={ index }
              name={ user.name }
              age={ user.age } />
      );
    });
  }
};


export default UsersListComponent;

Now, what I'm doing in my test files (I have a setup comprised of Mocha + Chai + Sinon, all working):

import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import sinon from 'sinon';
import UsersListComponent from '../src/usersListComponent';


describe('Test suite for UsersListComponent', () => {
  it('Correctly updates the state after AJAX call in `componentDidMount` was made', () => {
    const server = sinon.fakeServer.create();
    server.respondWith('GET', 'https://api.github.com/users', [
      200,
      {
        'Content-Type': 'application/json',
        'Content-Length': 2
      },
      '[{ "name": "Reign", "age": 26 }]'
    ]);
    let wrapper = mount(<UsersListComponent />);
    server.respond();
    server.restore();
    expect(wrapper.update().state().usersList).to.be.instanceof(Array);
    console.log(wrapper.update().state().usersList.length);
  });
});

State does not get updated, even though I call update() on wrapper. Length is still 0. Am I missing something here? Do I need to mock the server response in another way?

Thnx for the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can abstract the user list retrieval away from the react component via passing a function that returns a Promise so that instead of

  componentDidMount() {
    request('https://api.github.com/users', (err, res) => {
      if (!err && res.statusCode === 200) {
        this.setState({
          usersList: res.slice(0)
        });
      }
      else {
        console.log(err);
      }
    });
  }

Replace it with

  componentDidMount() {
     var comp = this;
     this.props.getUsers()
        .then(function(usersList) {
          comp.setState({
            usersList: usersList
          });
        })
        .catch(function (err) {
            console.log(err);
        });
  }

And inside your test mock that getUsers function:

    it('Correctly updates the state after AJAX call in `componentDidMount` was made', (done) => {

      let resolveGetUsers;

      let getUsers = function() {
        return new Promise(function (resolve, reject) {
                  resolveGetUsers = resolve;
                });
      }

      let wrapper = mount(<UsersListComponent getUsers={getUsers} />);

      resolveGetUsers([{ "name": "Reign", "age": 26 }]);


      // promise resolve happens in a subsequent event loop turn so move assertions inside setImmediate
      setImmediate(() => {

        expect(wrapper.update().state().usersList).to.be.instanceof(Array);
        ...

        done();
      });
    }

Note that I have done this and it works for me (even without the wrapper.update() part) and here I tried to apply it to your code example without running it..

Also note that it should work in cases other then componentDidMount too - like having an async action triggered after clicking a button for example..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...