Change element size using Jest
My solution is to mock getBoundingClientRect
(I'm currently using jest 16.0.1)
describe('Mock `getBoundingClientRect`', () => { beforeEach(() => { Element.prototype.getBoundingClientRect = jest.fn(() => { return { width: 120, height: 120, top: 0, left: 0, bottom: 0, right: 0, } }); }); it('should mock `getBoundingClientRect`', () => { const element = document.createElement('span'); const rect = element.getBoundingClientRect(); expect(rect.width).toEqual(120); });});
Don't forget to put the original value of getBoundingClientRect
back, because changing it might affect other tests.
Also, no need to do it in beforeEach
: beforeAll
will do.
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); });});
I took the idea from this answer