Copilot commented on code in PR #720:
URL: https://github.com/apache/shenyu-dashboard/pull/720#discussion_r4312239168
##########
src/routes/Document/ApiDoc.js:
##########
@@ -36,31 +36,27 @@ import ApiContext from "./components/ApiContext";
function ApiDoc() {
const [tagDetail, setTagDetail] = useState({});
const [apiDetail, setApiDetail] = useState({});
- const [apiData, setApiData] = useState({});
+ const [apiData, setApiData] = useState({ envProps: [] });
const [apiMock, setApiMock] = useState({});
const searchApiRef = React.createRef();
const initData = async () => {
- const { code, data = {} } = await getDocMenus();
- if (code === 200) {
- const { menuProjects = [] } = data;
- const createKey = (treeData, keys) => {
- treeData.forEach((item, index) => {
- const { children, id, name } = item;
- const key = [...keys, index].join("-");
- item.key = key;
- item.id = id;
- item.name = name;
- if (children?.length) {
- createKey(children, [...keys, index]);
- }
- });
- };
- createKey(menuProjects, []);
- data.menuProjects = menuProjects;
- setApiData(data);
- }
+ const { code, data } = await fetchShenYuDictByType({
+ type: "apidocEnv",
+ });
+ const list = Array.isArray(data) ? data : [];
+ const envProps =
+ code === 200
+ ? list
+ .filter((item) => item && item.enabled)
+ .map(({ dictName, dictValue, desc }) => ({
+ envLabel: dictName,
+ addressUrl: dictValue,
+ envDesc: desc,
+ }))
+ : [];
+ setApiData({ envProps });
Review Comment:
`initData()` does not handle request failures/rejections; if
`fetchShenYuDictByType` throws (network error, request wrapper throws on
non-2xx, etc.), the `useEffect`-triggered promise will reject and can produce
an unhandled rejection while leaving state unchanged. Wrap this in `try/catch`
and fall back to `setApiData({ envProps: [] })` (optionally with a non-blocking
user message) to keep the page stable under transient backend outages.
##########
src/routes/Document/ApiDoc.test.js:
##########
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import React from "react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import {
+ fetchShenYuDictByType,
+ getApiDetail,
+ getApiMockRequest,
+} from "../../services/api";
+import ApiDoc from "./ApiDoc";
+
+jest.mock("../../services/api", () => ({
+ fetchShenYuDictByType: jest.fn(),
+ getApiDetail: jest.fn(),
+ getApiMockRequest: jest.fn(),
+}));
+
+jest.mock("./components/SearchApi", () => {
+ const ReactModule = jest.requireActual("react");
+ return ReactModule.forwardRef(({ onSelect }, ref) => (
+ <button
+ type="button"
+ ref={ref}
+ onClick={() =>
+ onSelect([], { node: { props: { id: "api-1", isLeaf: true } } })
+ }
+ >
+ Select API
+ </button>
+ ));
+});
+
+jest.mock("./components/ApiInfo", () => {
+ const { default: ApiContext } =
jest.requireActual("./components/ApiContext");
+ return () => (
+ <ApiContext.Consumer>
+ {(context) => (
+ <pre data-testid="api-context">{JSON.stringify(context)}</pre>
+ )}
+ </ApiContext.Consumer>
+ );
+});
+jest.mock("./components/TagInfo", () => () => null);
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
+const selectApi = async () => {
+ getApiDetail.mockResolvedValue({
+ code: 200,
+ data: { id: "api-1", apiPath: "/orders" },
+ });
+ getApiMockRequest.mockResolvedValue({ code: 200, data: { id: "mock-1" } });
+ render(<ApiDoc />);
+ fireEvent.click(screen.getByText("Select API"));
+ await waitFor(() => {
+ expect(
+ JSON.parse(screen.getByTestId("api-context").textContent).apiMock.id,
+ ).toBe("mock-1");
+ });
+ return JSON.parse(screen.getByTestId("api-context").textContent);
Review Comment:
The helper `selectApi()` only waits for `apiMock` to be present, but the
dictionary-driven `envProps` update happens independently in `initData()`; this
can make the first test flaky because it reads `context.apiData.envProps`
immediately after `apiMock` is set. Make the helper (or the specific test) also
wait for the expected `envProps` state update (e.g., wait until envProps has
the expected length/contents) before returning the context.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]