0

我的应用程序从 中获取API,然后呈现数据。如果输入了不存在的值,则error boundary触发并捕获错误。

我正在ErrorBoundaryreact-error-boundary图书馆和图书馆QueryErrorResetBoundary使用react-query

使用我的React-Error-Boundary设置,我的应用程序在发生error boundary事件时有一个触发器,error并且能够error通过重置从state. 我目前对发生事件error boundary时的触发进行了通过测试error。现在我想测试是否error boundary可以从 triggererror boundary和 reset中恢复state。请让我知道如何使用Jestand来解决这个问题React Testing Library

应用组件

const ErrorFallback = ({ error, resetErrorBoundary }) => {
  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre style={{ color: "red" }}>{error.message}</pre>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  );
};

const App = () => {
  const [idQuery, setIdQuery] = useState(0);

  return (
    <div>
      <QueryErrorResetBoundary>
        <ErrorBoundary
          FallbackComponent={ErrorFallback}
          onReset={() => {
            setIdQuery(0);
          }}
          resetKeys={[idQuery]}
        >
          <Home idQuery={idQuery} setIdQuery={setIdQuery} />
        </ErrorBoundary>
      </QueryErrorResetBoundary>
      <ReactQueryDevtools initialIsOpen={true} />
    </div>
  );
};

应用程序.test.js

const App = () => {
    const [state, setState] = useState(0)
    return (
        <QueryErrorResetBoundary>
            <ErrorBoundary
                FallbackComponent={ErrorFallback}
                onReset={() => {
                    setState(0);
                }}
                resetKeys={[state]}
            >
                <Child />
            </ErrorBoundary>
        </QueryErrorResetBoundary>
    )
}

const Child = () => {
    throw new Error()
}

describe("Error Boundary", () => {
    beforeEach(() => {
        render(
            <App />
        );
    });

    it("should trigger the Error Boundary when an error occurs", () => {
        const errorMessage = screen.getByTestId("error-boundary-message");
        expect(errorMessage).toBeInTheDocument();
    });

    it("should recover from Error Boundary", () => {
        // ???
    })

});
4

1 回答 1

2

在不知道您实际尝试做什么的情况下,我怀疑这样的事情可能会帮助您入门:

const App = () => {
    const [isRecovered,setIsRecovered] = useState(false)
    return (
        <QueryErrorResetBoundary>
            <ErrorBoundary
                FallbackComponent={ErrorFallback}
                onReset={() => {
                    setIsRecovered(true)
                }}
                resetKeys={[isRecovered]}
            >
                <Child isRecovered={isRecovered} />
            </ErrorBoundary>
        </QueryErrorResetBoundary>
    )
}

const Child = ({isRecovered}) => {
    if(!isRecovered) throw new Error();
    return 'All Good';
}

至少您可以将代码添加ErrorBoundary到您的问题中。

于 2021-05-05T23:55:59.863 回答