【问题标题】:TypeError: getItems[props.action] is not a functionTypeError:getItems[props.action] 不是函数
【发布时间】:2021-12-14 01:23:13
【问题描述】:

我是反应测试的新手,我正在尝试使用此代码验证反应功能组件是否存在,但由于某种原因它抱怨其他东西 TypeError: getItems [ props.action ] is not a function

对此有任何帮助/建议,以验证组件是否存在?

interface SelectionListProps {
  actionArgs?: string | undefined;
  action: string;
  name?: string;
  identifier?: string;
  classes: {
    button_basic: string;
    formControl: string;
    selectionCard: string;
  };
}

export const SelectionList: React.FC<SelectionListProps> = (
  props
) => {
 
  const dispatch = useDispatch();

  const getItems = {
    analysers: (site: any) => dispatch(getAnalysers(site)),
    sites: (site: any) => dispatch(getSites()),
  } as any;

  const initializeCollapses = () => {
  
  };

  useEffect(() => {
    getItems[props.action](props.actionArgs).then(() => {
      initializeCollapses();
    });
  }, []);


  return (
    <List component="div" data-testid="SelectionListt">
    </List>
  );
};

我的测试代码:

import React from "react";
import { expect } from "@jest/globals";
import { render, screen, cleanup, fireEvent } from "@testing-library/react";
import { SelectionList } from "../SelectionList";
import { Provider } from "react-redux";
import { store } from "../../redux/store";

import "@testing-library/jest-dom/extend-expect";

function handleUpdateClick(event: any, type = "") {}
test("test", () => {
  render(
    <Provider store={store}>
      <SelectionList
        classes={{ button_basic: "", formControl: "", selectionCard: "" }}
        action={""}
        actionArgs={""}
     
      />
    </Provider>
  );
  const SelectionCardElement = screen.getByTestId("SelectionListt");
  expect(SelectionCardElement).toBeInTheDocument();
});

【问题讨论】:

    标签: reactjs typescript function unit-testing jestjs


    【解决方案1】:

    您正在为action 名称传递一个空字符串,但getItems[""] 不匹配任何函数,因为getItems 的值是:

    const getItems = {
        analysers: (site: any) => dispatch(getAnalysers(site)),
        platforms: (site: any) => dispatch(getPlatforms(site)),
        brokers: (site: any) => dispatch(getBrokers(site)),
        cameras: (site: any) => dispatch(getCameras(site)),
        sites: (site: any) => dispatch(getSites()),
    }
    

    还有 getItems 的所有函数,但最后一个函数需要一个 site 参数。但是,目前您也为参数传递了一个空字符串。在 sites 函数中,您可以删除未使用的 sites 参数

    【讨论】:

    • 现在它工作了,谢谢,为什么我会得到这个:属性'toBeInTheDocument'不存在于类型'Matchers'.ts(2339)
    • 我过去见过这种类型的错误。该属性实际上存在于expect 上,但在类型声明中不知道,如果这有意义的话。我认为它由import '@testing-library/jest-dom/extend-expect' 处理,但我看到你拥有它。难道是来自另一个测试文件?
    • 我上周得到了它并用这个修复了它:import '@testing-library/jest-dom/extend-expect' 但现在我将我的组件名称从 SelectionCard 重命名为 SelectionList,然后得到了这个。 ..并且该导入不再起作用
    • 哈,我想可能是因为你单独导入了expect。尝试删除行import { expect } from "@jest/globals";
    • 那里根本不需要?
    猜你喜欢
    • 2020-09-11
    • 2020-11-01
    • 2017-05-06
    • 2019-12-20
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多