Skip to content

Commit

Permalink
docs: Use Object.defineProperty() for stubbing global properties
Browse files Browse the repository at this point in the history
Direct assignments to `window` properties fails silently if they are not
writable, so `Object.defineProperty()` should be used when stubbing
global properties.

Closes jestjs#9287
  • Loading branch information
vvanpo committed Dec 9, 2019
1 parent 012fc8b commit 9b50e0f
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions docs/ManualMocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,9 @@ If some code uses a method which JSDOM (the DOM implementation used by Jest) has
In this case, mocking `matchMedia` in the test file should solve the issue:

```js
window.matchMedia = jest.fn().mockImplementation(query => {
return {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: {
matches: false,
media: query,
onchange: null,
Expand All @@ -151,7 +152,7 @@ window.matchMedia = jest.fn().mockImplementation(query => {
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
};
},
});
```

Expand Down

0 comments on commit 9b50e0f

Please sign in to comment.