Jest react-native Hook无法正确嘲笑

时间:2020-06-26 15:02:13

标签: javascript react-native unit-testing testing jestjs

问题

我需要在Jest中模拟react-native钩子useWindowDimensions来对函数进行单元测试,但是返回的模拟值不是我定义的模拟值。

有人知道为什么使用错误的值创建我的模拟吗?如何解决它?

代码

我正在进行单元测试的功能

export function windowDimensions(): WindowDimensions {
         const windowWidth = Math.round(useWindowDimensions().width);
         const windowHeight = Math.round(
           useWindowDimensions().height
         );
         const minWindowDimension = Math.min(windowWidth, windowHeight);
         const maxWindowDimension = Math.max(windowWidth, windowHeight);
         return { minWindowDimension, maxWindowDimension };
       }

单元测试

  • 单元测试返回{“ maxWindowDimension”:1334,“ minWindowDimension”:750}
  • 使用下面创建的模拟,它应返回{“ maxWindowDimension”:400,“ minWindowDimension”:200}
  describe("windowDimensions return value", () => {
    let dummyComponent;
    let mockWindowDimensions;
      const DummyComponent = () => {
        // const { windowDimensions } = props;
    mockWindowDimensions = jest.fn(() => windowDimensions());
      mockWindowDimensions();
        return <View />;
      };

    beforeAll(() => {
    
      jest.mock("react-native", () => ({
        ...jest.requireActual("react-native"),
        useWindowDimensions: () => ({
          width: 100,
          height: 200
        })
      }));
    });
    it("should return windowWidth", () => {
      dummyComponent = render(
        <DummyComponent />
      );
      expect(mockWindowDimensions).toHaveReturnedWith({
        minWindowDimension: 100,
        maxWindowDimension: 200
      });
    });
  });

0 个答案:

没有答案