UNPKG

@shopify/jest-dom-mocks

Version:
65 lines (61 loc) 1.94 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); class MatchMedia { constructor() { this.originalMatchMedia = null; } mock(media = defaultMatcher) { if (this.originalMatchMedia !== null) { throw new Error('You tried to mock window.matchMedia when it was already mocked.'); } this.originalMatchMedia = window.matchMedia; this.setMedia(media); } restore() { if (this.originalMatchMedia === null) { throw new Error('You tried to restore window.matchMedia when it was already restored.'); } window.matchMedia = this.originalMatchMedia; this.originalMatchMedia = null; } isMocked() { return this.originalMatchMedia !== null; } setMedia(media = defaultMatcher) { this.ensureMatchMediaIsMocked(); window.matchMedia = query => mediaQueryList(media(query)); } ensureMatchMediaIsMocked() { if (this.originalMatchMedia === null) { throw new Error('You must call matchMedia.mock() before interacting with the mock matchMedia.'); } } } function defaultMatcher() { return { media: '', addListener: noop, addEventListener: noop, removeListener: noop, removeEventListener: noop, onchange: noop, dispatchEvent: () => false, matches: false }; } function mediaQueryList(values) { // Explictly state a return type as TypeScript does not attempt to shrink the // type when using Object spread. Without the explicit return type TypeScript // exports a type that exposes the internals of `MediaQueryList` (which // changed in TS 3.1.0). // This ensures that this function can be used in projects that use any // version of Typescript instead of only <3.1.0 or >= 3.1.0 depending on the // version that this library was compiled using. return { ...defaultMatcher(), ...values }; } function noop() {} exports["default"] = MatchMedia; exports.mediaQueryList = mediaQueryList;