環境
- Jest: v24.8.0
モチベーション
Jestでwindow.location.hrefをmockしたい。
結論
下記公式ドキュメントを参照。
https://jestjs.io/docs/en/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
window.location.hrefのmock
describe('mock window.location.href', () => { beforeEach(() => { delete window.location; }); test('hogehoge', () => { Object.defineProperty(window, 'location', { configurable: true, value: { href: 'https://example.com/', }, }); expect(window.location.href).toBe('https://example.com/'); }); });