不要忘记把原来的值放getBoundingClientRect
回去,因为改变它可能会影响其他测试。
此外,无需在beforeEach
:beforeAll
中执行此操作。
describe("Mock `getBoundingClientRect`", () => {
let boundingClientRect;
const originalGetBoundingClientRect = Element.prototype.getBoundingClientRect;
beforeAll(() => {
Element.prototype.getBoundingClientRect = () => boundingClientRect;
});
afterAll(() => {
Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
});
it("should mock `getBoundingClientRect`", () => {
const element = document.createElement("div");
boundingClientRect = new DOMRect(0, 0, 120, 120);
const rect = element.getBoundingClientRect();
expect(rect.width).toEqual(120);
});
});
我从这个答案中得到了这个想法