簡體   English   中英

測試依賴於 Promise 的 React Native 功能組件

[英]Testing React Native Functional Component With Dependency on Promise

我在 React Native 中有一個功能組件。

import { ReactElement, useEffect, useState } from "react-test-renderer/node_modules/@types/react";
import SpecialObject from "./SpecialObject";
import { getPromisedObject } from "./AccessFunctions";

export function PromiseDependencyComponent(): ReactElement {
  const [val, setVal] = useState<SpecialObject>(new SpecialObject());

  const promisedVal: Promise<SpecialObject> = getPromisedObject();

  useEffect(() => {
    setInterval(() => {
      promisedVal.then( (obj) =>
        setVal(obj); 
      );
    }, 250);
  }, []);

  return (<Text>{val.getSomeField()}</Text>);
}

我希望能夠測試在呈現組件時是否正確檢索了承諾的SpecialObject 這就是我現在所擁有的:

import * as React from "react";
import renderer from "react-test-renderer";
import PromiseDependencyComponent from "../PromiseDependencyComponent";

it("PromiseDependencyComponent renders correctly", () => {
  const componentRenderer = renderer.create(<PromiseDependencyComponent />);
  // I've also tried using timers and componentRenderer.update() and neither worked for me.
  const tree = componentRenderer.toJSON();

  expect(tree).toMatchSnapshot();
});

該測試執行並且沒有任何中斷,我只是沒有看到與運行應用程序時看到的相同的東西。 當我運行應用程序時,我看到承諾的值在 250 毫秒延遲后顯示。 但我的問題是我想在我的測試快照中看到更新/承諾的值。

所以我在我的應用程序中看到的是這樣的:

  <!-- This the updated/promised SpecialObject. -->
  <Text>5</Text>

但是我在我的測試快照中得到了這樣的東西:

  <!-- This just comes from a new instance of SpecialObject, which is the initialized component state. -->
  <Text>0</Text>

在我的組件上調用某種更新的最簡單/最干凈的方法是什么,以便我可以在呈現組件時驗證承諾是否得到滿足?

首先,有一個流行的測試庫用於處理 React 中的各種測試場景,它被稱為@testing-library/react 我強烈建議你在 React 組件測試中使用它。

至於你問的問題, @testing-library/reactwaitForawait findBy... ,你可以將它們用於異步測試。 (見異步方法

所以一個例子是這樣的:

import {render, screen} from "@testing-library/react"
import MyAsyncComponent from "./MyAsyncComponent"

describe("My Async Component", () => {
  it("Updates after promise resolves", async () => {
    render(<MyAsyncComponent/>)

    const myAsyncResult = await screen.findByText("5");

    expect(myAsyncResult).toBeInTheDocument();

  })
})

暫無
暫無

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

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