Skip to content

Commit

Permalink
Add explanation on how to mock methods not implemented in JSDOM (#6187)
Browse files Browse the repository at this point in the history
  • Loading branch information
timkraut authored and cpojer committed May 16, 2018
1 parent 7f74710 commit fef9032
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@

### Chore & Maintenance

* `[docs]` Add explanation on how to mock methods not implemented in JSDOM
* `[jest-jasmine2]` Simplify `Env.execute` and TreeProcessor to setup and clean
resources for the top suite the same way as for all of the children suites
([#5885](https://github.com/facebook/jest/pull/5885))
Expand Down
37 changes: 37 additions & 0 deletions docs/ManualMocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,40 @@ the test file. But often you need to instruct Jest to use a mock before modules
use it. For this reason, Jest will automatically hoist `jest.mock` calls to the
top of the module (before any imports). To learn more about this and see it in
action, see [this repo](https://github.com/kentcdodds/how-jest-mocking-works).

### Mocking methods which are not implemented in JSDOM

If some code uses a method which JSDOM (the DOM implementation used by Jest)
hasn't implemented yet, testing it is not easily possible. This is e.g. the case
with `window.matchMedia()`. Jest returns
`TypeError: window.matchMedia is not a function` and doesn't properly execute
the test.

In this case, mocking `matchMedia` in the test file should solve the issue:

```js
window.matchMedia = jest.fn().mockImplementation(query => {
return {
matches: false,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn(),
};
});
```

This works if `window.matchMedia()` is used in a function (or method) which is
invoked in the test. If `window.matchMedia()` is executed directly in the tested
file, Jest reports the same error. In this case, the solution is to move the
manual mock into a separate file and include this one in the test **before** the
tested file:

```js
import './matchMedia.mock'; // Must be imported before the tested file
import {myMethod} from './file-to-test';

describe('myMethod()', () => {
// Test the method here...
});
```

0 comments on commit fef9032

Please sign in to comment.