Problem
I need to mock the react-native hook useWindowDimensions in Jest to do a unit test on my function, but the mock values returned are not the mock values I've defined.
Does anyone know why my mock is being created with the wrong values and how to fix it?
Code
Function I'm Unit Testing
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 };
}
Unit Test
- The unit test returns {"maxWindowDimension": 1334, "minWindowDimension": 750}
- With the mock I created below, it should return {"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
});
});
});
Aucun commentaire:
Enregistrer un commentaire