【问题标题】:My react test are not working because of api call由于 api 调用,我的反应测试不起作用
【发布时间】:2019-09-20 16:25:05
【问题描述】:

我正在为调用 api 来收集数据的组件编写测试。问题是我在测试中的视图在从 api 收集数据之前呈现并且 HTML 部分中的所有字段都是空的。

我的组件视图

export default class ExampleView extends React.Component<Props, {}> {
  constructor(props: Props) {
    super(props);
    this.GetData();
  }
  GetData = () => {
    //Call api and get data set in local variable
 };

我的测试用例

describe('<ExampleView />', () => {

  let res;
  beforeEach(() => {
    res = sinon.spy(RailsConnection.prototype, 'get');
    mock.onAny().reply(200, object);
  });

  afterEach(() => {
    res.restore();
  });

  it('renders without errors  ', () => {
    html = mount(<ExampleView/>);
    console.log(html.html());
  });
};

我的 html 没有数据

【问题讨论】:

  • 您是在状态还是在实例上设置?如果发生异步查询,初始通道将呈现为空
  • 它在实例中
  • 需要查看其余的组件代码。我推荐 react-testing-library

标签: node.js reactjs


【解决方案1】:

您需要将 API 调用放在 componentDidMount 方法中,以确保在组件完成第一次渲染之前返回数据。您也没有正确绑定您的方法:

export default class ExampleView extends React.Component<Props, {}> {
  constructor(props: Props) {
    super(props);
    this.getData = this.getData.bind(this);
  }
  getData = () => {
    //Call api and get data set in local variable
  };

  componentDidMount() {
     this.getData();
  }

  render() {
    return <div/>;
  }
}

【讨论】:

  • 让我试一试
  • 请发布您用于组件的真实代码。
【解决方案2】:

解决了
it('renders without errors  ', () => {
    html = mount(<ExampleView/>);
    await new Promise(resolve => setTimeout(resolve))
    html.update()
    console.log(html.html());
  });

【讨论】:

    猜你喜欢
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多