输入未在反应测试库上更新,因此测试失败,但它确实在实际应用程序上更新

Gio*_*ini 3 redux react-testing-library

我想测试当我在输入(inputA)中键入一个值时,另一个输入(inputB)会更新为一个值。

inputA 接受邮政编码,例如:“10999”,在 inputB 显示位置后:“Berlin”

这适用于实际的应用程序,我输入 inputA,然后 inputB 会更新。

当 ome 在 inputA 上键入时,会调度一个操作,然后 inputB 从 redux 状态获取一个新值。

这是我的测试代码,您知道为什么它在测试中不使用“Ort”占位符更新输入,但在实际应用程序中却这样做吗?

import { render, withIntl, withStore, configureStore, withState } from "test-utils-react-testing-library";
import { screen, fireEvent, withHistory, withRoute, within } from "@testing-library/react";
import configureMockStore from 'redux-mock-store';

import ProfileForm from "./ProfileForm";
import PersonalDetails from "../PersonalDetails/PersonalDetails";

const STATE = {
  locations: { locations: {} },
  streets: { streets: {} },
  password: {}
};

const mockStore = configureMockStore();
const STORE = mockStore({
  streets: {
    isFetching: false,
  },
  locations: {
    locations: {
      isFetching: false,
    },
  },
  user: {
    session: {
      impersonated_access_token: "",
    },
    updateError: "error",
  },
});

const props = {
  id: "user1",
  user: { email: "max@muster.de" },
  locations: {},
  onSubmit: jest.fn(),
};
  
beforeEach(jest.resetAllMocks);

describe("ProfileForm", () => {
    describe("on personal details change", () => {
      it("auto selects only location when postalcode becomes selected", () => {
        const locations = { electricity: { [PLZ_1]: [LOCATION_OBJ_1] } };
        const user = { postalcode: null };

        render(<ProfileForm {...props} user={user} locations={locations} />, [...decorators, withStore(STORE)]);
        
        const input = screen.getByPlaceholderText("PLZ");
        fireEvent.change(input, { target: { value: "10999" } })
        
        screen.debug(screen.getByPlaceholderText("PLZ"))
        screen.debug(screen.getByPlaceholderText("Ort"))

        expect(screen.getByPlaceholderText("Ort")).toHaveValue("Berlin");
      });

});
Run Code Online (Sandbox Code Playgroud)

Vla*_*nin 6

我猜您的输入尚未更新。

尝试使用waitforhttps://testing-library.com/docs/dom-testing-library/api-async#waitfor

import { waitFor } from "@testing-library/react";

const inputNode = screen. getByPlaceholderText("Ort");
//  keep in mind that you need to make your test async like this
//  it("auto selects only location when postalcode becomes selected", async () => {
await waitFor(() => expect(inputNode).toHaveValue("Berlin"));
Run Code Online (Sandbox Code Playgroud)

如果不起作用,请尝试添加超时:

await waitFor(() => expect(inputNode).toHaveValue("Berlin"), { timeout: 4000 });
Run Code Online (Sandbox Code Playgroud)

  • 尝试过,但出现此错误:警告:`无法在未安装的组件上执行 React 状态更新。这是一个空操作,但它表明应用程序中存在内存泄漏。要修复此问题,请取消 useEffect 清理函数中的所有订阅和异步任务。` 不知道它来自哪里:( (2认同)
  • @GiorgioMartini 你有没有弄清楚这一点?我有类似的问题。 (2认同)