这是对上述组件的测试
import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Provider } from "react-redux";
import configureStore from "redux-mock-store";
import AddDeviceWrapper from "../AddDeviceWrapper";
describe("Form", () => {
test("Handles input changes with saveDeviceChange when typing or editing an value", () => {
const handleFormInputMock = jest.fn();
const store = configureStore();
render(
<Provider store={store}>
<AddDeviceWrapper
system_name={""}
type={""}
hdd_capacity={""}
saveDeviceChange={handleFormInputMock}
/>
</Provider>
);
const systemName = screen.getByLabelText("System Name *");
const type = screen.getByLabelText("Type *");
const hddCapacity = screen.getByLabelText("HDD Capacity (GB) *");
userEvent.type(systemName, "yoda_mac");
expect(handleFormInputMock).toHaveBeenCalled();
expect(handleFormInputMock).toHaveBeenCalledWith("systemName", "yoda_mac");
userEvent.type(type, "MAC");
expect(handleFormInputMock).toHaveBeenCalledWith("type", "MAC");
userEvent.type(hddCapacity, { target: { value: 500 } });
expect(handleFormInputMock).toHaveBeenCalledWith("hddCapacity", 500);
});
});
测试失败并显示以下消息
<块引用>反应脚本测试 失败 src/components/tests/AddDeviceWrapper.test.js 形式 ✕ 在输入或编辑值时使用 saveDeviceChange 处理输入更改(32 毫秒)
● 表单 › 在输入或编辑值时使用 saveDeviceChange 处理输入更改
TypeError: store.getState is not a function
11 | const store = configureStore();
12 |
> 13 | render(
| ^
14 | <Provider store={store}>
15 | <AddDeviceWrapper
16 | system_name={""}
控制台错误
警告:失败的道具类型:提供给 store
的类型为 function
的无效道具 Provider
,预期为 object
。
at Provider (/Users/yongyili/Documents/coding-assessments/devices-clientapp/node_modules/react-redux/lib/components/Provider.js:21:20)
12 |
13 | render(
> 14 | <Provider store={store}>
| ^
15 | <AddDeviceWrapper
16 | system_name={""}
17 | type={""}
答案 0 :(得分:1)
来自 configureStore()
的 redux-mock-store
函数返回一个创建者函数。这是在您想向其中添加中间件的情况下。要获得模拟商店,您应该这样做:
const createStore = configureStore();
const mockStore = createStore();
然后您可以在其余测试中照常使用 mockStore
。