【问题标题】:Use enzyme to test table which fetches data though post request使用酶测试通过发布请求获取数据的表
【发布时间】:2017-11-13 17:08:32
【问题描述】:

我有一个react bootstrap table,它可以获取如下实时数据。我想添加一个使用酶的单元测试。但是,该表需要先从我的 url 获取实时数据。

我不想获取数据,因为我没有在我的数据库中插入测试数据。有没有办法使用假数据进行测试而不是发送 post 请求。

class MyTable extends Component {
  getAttachments(){
    const url = `${myUrl}`;
    const data = {id: this.props.id};
    agent.post(url)
      .type('json')
      .set(getAuthHeader())
      .send(data)
      .then( (result) => {
      this.setState({data: result.body});
      console.log(result.body);
      }).catch(error => {
        console.error(error);
      });
  }

  componentWillMount(){
    this.getAttachments();
  }

  render() {
    return (
      <div className="App">
        <BootstrapTable data={this.state.data} version='4'>
          <TableHeaderColumn dataField="id" isKey={true} dataAlign="center" dataSort={true}>Product ID</TableHeaderColumn>
          <TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn>
          <TableHeaderColumn dataField="price" dataFormat={priceFormatter}>Product Price</TableHeaderColumn>
        </BootstrapTable>
      </div>
    );
  }
}

【问题讨论】:

    标签: reactjs mocha.js enzyme


    【解决方案1】:

    sinon 可用于模拟请求和此类单元测试:

    const promiseEmpty = Promise.resolve([]);
    
    it('should render without exploding', () => {
        const putRequest = sinon.stub(agent.Request.prototype, 'send', () => promiseEmpty);
        const wrapper = shallow(<AttachmentTable {...minProps}/>);
        putRequest.restore();
        return promiseEmpty.then(() => {
          wrapper.update();
          expect(wrapper.length).to.equal(1);
        });
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多