簡體   English   中英

等待兩個單獨的承諾解決,以便更新狀態

[英]Waiting for two separate promises to resolve so state is updated

所以我正在測試一個改變狀態的反應組件按鈕點擊。 在呈現組件時,我需要一個承諾來解決,以便呈現按鈕並因此可點擊。 我通過在組件狀態更新時將按鈕單擊放置在 setTimeout 內來完成此操作。 但是,在單擊按鈕后,由於要解決承諾,需要更新組件狀態。 下面我舉個例子

class App extends component {
     constructor(props){
     this.state ={
         hasError = false;
         loading = true;
   }
}

componentdidMount(){
    this.apiGetFunc();

apiGetFunc(){
  this.setState({hasError: false});
  this.setState({loading = false});
}

onClickFunc{
   this.middleWareCalltoAPI.then(
      respone =>{ this.setState({hasError: false})},
      errorRespone =>{ this.setState({hasError = true})};
   )
}


renderer(){
   return (
     <Card>
     {!this.state.hasError && !this.state.loading && (
     <div>
     <Button>
        onClick = {this.onClickfunc}
     </Button>
     </div>
     </Card>
     )}
   )
}

現在這是我的測試的樣子

test("Save user permissions", done => {
  mock.onGet("anAPI.php").reply(200, mockData); //THIS IS NEEDED TO RENDER THE BUTTON
  const wrapper = shallow(<App />);

  setTimeout(() => {
    wrapper.find("Button").simulate("click"); //THIS CLICK SHOULD CHANGE hasError to true
    expect(wrapper.state.hasError).toEqual(true) //THIS FAILS
    done();
  }, 0);
});

我試過嵌套 setTimeouts 以便點擊的承諾可以解決,但這似乎不起作用。 我試圖盡可能地精簡我的代碼,以便它具有可讀性。 如果您需要我提供更多背景信息,請告訴我。

編輯:使代碼更接近我實際擁有的

上面的示例代碼中有很多錯誤,我強烈建議您在嘗試繼續之前花一些時間做一些簡單的 React 教程。

盡管如此,這里有一個工作示例......

工作示例https : //codesandbox.io/s/xj53m8lwvz (您可以通過單擊屏幕左下角附近的“ Tests選項卡來運行測試)

api/fakeAPI.js

const data = [
  {
    userId: 1,
    id: 1,
    title: "delectus aut autem",
    completed: false
  },
  {
    userId: 1,
    id: 2,
    title: "quis ut nam facilis et officia qui",
    completed: false
  },
  {
    userId: 1,
    id: 3,
    title: "fugiat veniam minus",
    completed: false
  },
  {
    userId: 1,
    id: 4,
    title: "et porro tempora",
    completed: true
  },
  {
    userId: 1,
    id: 5,
    title: "laboriosam mollitia et enim quasi adipisci quia provident illum",
    completed: false
  }
];

export const fakeAPI = {
  failure: () =>
    new Promise((resolve, reject) => {
      setTimeout(() => {
        reject("No data was found!");
      }, 1000);
    }),
  success: () =>
    new Promise(resolve => {
      setTimeout(() => {
        resolve(data);
      }, 1000);
    })
};

組件/應用程序/App.js

import React, { Component } from "react";
import ShowData from "../ShowData/showData";
import ShowError from "../ShowError/showError";
import { fakeAPI } from "../../api/fakeAPI";

export default class App extends Component {
  state = {
    data: [],
    hasError: "",
    isLoading: true
  };

  componentDidMount = () => {
    this.fetchData();
  };

  fetchData = () => {
    fakeAPI
      .success()
      .then(data => this.setState({ isLoading: false, data: data }))
      .catch(err => this.setState({ isLoading: false, hasError: err }));
  };

  handleClick = () => {
    this.setState({ isLoading: true, data: [] }, () => {
      fakeAPI
        .failure()
        .then(res => this.setState({ isLoading: false, hasError: "" }))
        .catch(err => this.setState({ isLoading: false, hasError: err }));
    });
  };

  render = () => (
    <div className="app-container">
      {this.state.isLoading ? (
         <ShowLoading />
      ) : this.state.hasError ? (
        <ShowError error={this.state.hasError} />
      ) : (
        <ShowData data={this.state.data} handleClick={this.handleClick} />
      )}
    </div>
  );
}

components/App/__test__/App.test.jsmountWrap是一個自定義函數,您可以在test/utils/index.js找到, WaitForExpect是一種更簡單的方法,可以在 jest 的默認 5 秒超時內等待斷言為true

import React from "react";
import { mountWrap } from "../../../test/utils";
import WaitForExpect from "wait-for-expect";
import App from "../App";

const initialState = {
  data: [],
  hasError: "",
  isLoading: true
};

const wrapper = mountWrap(<App />, initialState);
describe("App", () => {
  it("renders without errors", () => {
    expect(wrapper.find("div.app-container")).toHaveLength(1);
  });

  it("initally shows that it's loading", () => {
    expect(wrapper.state("isLoading")).toBeTruthy();
    expect(wrapper.find("div.loading")).toHaveLength(1);
  });

  it("renders data and shows an Update button", async () => {
    await WaitForExpect(() => {
      wrapper.update();
      expect(wrapper.state("isLoading")).toBeFalsy();
      expect(wrapper.find("div.data")).toHaveLength(5);
      expect(wrapper.find("button.update")).toHaveLength(1);
    });
  });

  it("shows an error once the button has been clicked", async () => {
    wrapper.find(".update").simulate("click");
    await WaitForExpect(() => {
      wrapper.update();
      expect(wrapper.state("isLoading")).toBeFalsy();
      expect(wrapper.state("hasError")).toBe("No data was found!");
      expect(wrapper.find("div.error")).toHaveLength(1);
    });
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM