1

I've implemented Maxime's solution for this question about "window.matchMedia" not being found, but when I run my test I get this error: TypeError: j.window.MatchMedia is not a function.

I'm not sure what I need to do to get the "j" to resolve, since if I alter the first line from

Object.defineProperties(window, "matchMedia" {

to

Object.defineProperties(j.window, "matchMedia" {

Jest tells me that it can't resolve "j", which makes sense but doesn't help me understand and fix the error.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Shafiq Jetha
  • 1,337
  • 16
  • 30
  • See https://jestjs.io/docs/en/manual-mocks and https://stackoverflow.com/questions/39830580/jest-test-fails-typeerror-window-matchmedia-is-not-a-function – Matt Fletcher Jun 27 '20 at 13:55
  • Does this answer your question? [Jest test fails : TypeError: window.matchMedia is not a function](https://stackoverflow.com/questions/39830580/jest-test-fails-typeerror-window-matchmedia-is-not-a-function) – Matt Fletcher Jun 27 '20 at 13:55
  • @MattFletcher I think my specific issue was around the 'j' in front of 'window', though I didn't come across the post you liked to when I was looking for existing questions. I'll give this a go, thanks for the link. – Shafiq Jetha Jun 27 '20 at 17:58

2 Answers2

5

After looking into the jest solution and the documentation briefly about how it's a mock up function... so this variable can be mock up of a function as well.

 let mock = () => {}

Resolves this TypeError except the j on angular/universal server.ts 10

Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: (query: any) => { return {
  matches: false,
  media: query,
  onchange: null,
  addListener: mock, // deprecated         
  removeListener: mock, // deprecated
  addEventListener: mock,
  removeEventListener: mock,
  dispatchEvent: mock,
 }}
});
Gavin Chebor
  • 265
  • 3
  • 5
1

If you are using @angular-builders/jest you can add this to your angular.json:

    "test": {
      "builder": "@angular-builders/jest:run",
      "options": {
        "globalMocks": [
          "matchMedia"
        ]
      }
    },

This builder allows you to run your jest tests with ng test as well. Documentation on how to install this can be found here: https://github.com/just-jeb/angular-builders/tree/master/packages/jest#builder-options

Daan van Hulst
  • 1,426
  • 15
  • 32