开玩笑 - 模拟 - toHaveBeenCalled() 未按预期工作?

问题描述 投票:0回答:2

不明白为什么当我尝试以下面的方式进行模拟时,Mock 函数没有显示 tohaveBeenCalled

//我的App.js

import useAuth from "./src/hooks/useAuth";
import useBrunch from "./src/hooks/useBrunch";
import { someFunct } from "./functional";

export default function App() {
  const { funct } = useBrunch();
  return (
    <>
      <Max funct={funct} />
    </>
  );
}

function Max() {
  const LoginSchema = object().shape({
    emailId: string(),
    password: string(),
  });

  const { funct } = useBrunch();
  // const { funct, sas } = useBrunch();
  // const [flag, setFlag] = React.useState(false);
  //const { someFunct } = useAuth();
  return (
    <Formik
      initialValues={{ emailId: "[email protected]" }}
      onSubmit={(a, v) => {
        funct(a);
      }}
      validationSchema={LoginSchema}
    >
      {({ handleSubmit, handleBlur, values, dirty, touched, errors }) => {
        return (
          <View style={styles.container}>
            <Text>Open up App.js to start working on your app!</Text>
            <StatusBar testID="someId" style="auto" />
            <CheckBox />
            <TouchableOpacity
              testID="masa"
              disabled={false}
              onPress={handleSubmit}
            >
              <View>
                <Text testID="hello">SOmething</Text>
              </View>
            </TouchableOpacity>
            <Button testID="something" title="someddd" onPress={() => {}} />
          </View>
        );
      }}
    </Formik>
  );
}

export { Max };

//我的hooks/useBrunch.js方法

const useBrunch = () => {
  console.log("called");
  const funct = (a) => {
    console.log("funct executed");
  };
  return { funct };
};

export default useBrunch;

//我的App.test.js文件

import React from "react";
import { render, act, waitFor, fireEvent } from "@testing-library/react-native";
import useBrunch from "./src/hooks/useBrunch";
import { Max } from "./App";

jest.mock("./src/hooks/useBrunch", () =>
  jest.fn(() => ({
    funct: jest.fn((a) => {
      console.log(a, "called");
      return a;
    }),
  }))
);

describe("Login something", () => {
  it("first clss", async () => {
    let { getByTestId, toJSON } = render(<Max />);
    const something = getByTestId("masa");
    await waitFor(() => {
      fireEvent.press(something);
    });

    expect(useBrunch().funct).toHaveBeenCalled();
    
  });
});

预期-模拟按钮上预期的输出应该成功 我在模拟函数中有控制台被调用,并且还显示参数, 但无法在 toHaveBeenCalled() 或类似的玩笑方法下注册它

有人可以帮忙吗?!

reactjs react-native jestjs mocking react-testing-library
2个回答
0
投票

尝试给出这样的东西:

const mockFunct = jest.fn((a) => {
  console.log(a, "called");
  return a;
})
jest.mock("./src/hooks/useBrunch", () =>
  jest.fn(() => ({
    funct: mockFunct
  })
));

然后

 expect(mockFunct).toHaveBeenCalled();

0
投票

建议的答案如何运作?它不应该抛出以下错误吗?

ReferenceError:

jest.mock()
的模块工厂不允许 引用任何超出范围的变量。

© www.soinside.com 2019 - 2024. All rights reserved.