在Ajax之后渲染不同的Test React组件(Jest& Enzyme)

时间:2017-11-04 23:54:01

标签: reactjs jestjs enzyme enzyme-to-snapshot

如果一个组件(在这种情况下说是<Person />)如果完全呈现但仅在<Loading />完成之后(这是在成功的Ajax调用之后)?

我正在使用Jest和Enzyme。但是,使用Enzyme,快照将是具有Loading组件的Person,而不是Ajax调用之后的最终渲染状态。我需要模拟我的Ajax调用,但是使用模拟然后拍摄快照之后会是什么样子?

class Person extends Component {
...
   componentWillMount() {
     // ajax call to person data, including ID
     // on successful Ajax completion, set state.personID and other values, etc. 

     axios.get('.../person', {
      params: {
        AltID: 12345
        }
     }).then(function (response) {
      this.setState({personID: response.data.personID,...});

     }).catch(function (error) {
      ...
     });
   }

    render() {
      if (!this.state.personID) {
        return (
          <div className="App">
            <Loader />
          </div>);
      }
      return (
        <div className="App">
          ...
          Person ID: {{this.state.personID}}
          ...
        </div>
      );
    }
}

酶快照测试(需要修饰):

describe('Person', () => {
  it('renders correctly', () => {
    const rendered = renderer.create(<Person />);
    expect(rendered.toJSON()).toMatchSnapshot();
  });
});

最后,在测试中设置this.setState({personID: value})的工作并不是我想要的,因为在真正未发布的场景中,componentWillMount执行Ajax调用来验证用户。目前,这已被推送到错误页面。

1 个答案:

答案 0 :(得分:0)

您可以模拟api调用https://facebook.github.io/jest/docs/en/tutorial-async.html或者您可以进行2次测试,一次条件为True,另一次条件为False。您的api调用只是将状态从一种状态更改为另一种状态,因此根据状态,您需要测试一切是否正确呈现。

示例:

test('the data is peanut butter', done => {
  function callback(data) {
    expect(data).toBe('peanut butter');
    done();
  }W

  fetchData(callback);
});
相关问题