Categories
JavaScript Answers

How to fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests?

Sometimes, we want to fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests.

In this article, we’ll look at how to fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests.

How to fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests?

To fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests, we can add a mocked version of the window.matchMedia method.

To do this, we write

describe("Test", () => {
  beforeAll(() => {
    Object.defineProperty(window, "matchMedia", {
      writable: true,
      value: jest.fn().mockImplementation(query => ({
        matches: false,
        media: query,
        onchange: null,
        addListener: jest.fn(),
        removeListener: jest.fn(),
        addEventListener: jest.fn(),
        removeEventListener: jest.fn(),
        dispatchEvent: jest.fn(),
      }))
    });
  });
});

to call Object.defineProperty to add the matchMedia property to window.

We set it to a mocked function that we get by calling jest.fn.

And we call mockImplementation with a function that returns a bunch of properties that are returned by matchMedia like matches, media, onChange, etc.

We mock the methods with jest.fn and set the rest to different fake values.

We put the mock code in the beforeAll callback so it’s called before all tests.

Conclusion

To fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests, we can add a mocked version of the window.matchMedia method.

Categories
JavaScript Answers

What is the difference between describe and it in Jest?

In this article, we’ll look at the difference between describe and it in Jest.

What is the difference between describe and it in Jest?

The difference between describe and it in Jest is that describe lets us divide our test suite into sections.

it is called to create individual tests which is used in the describe callback.

For instance, we write

const myBeverage = {
  delicious: true,
  sour: false,
};

describe('my beverage', () => {
  it('is delicious', () => {
    expect(myBeverage.delicious).toBeTruthy();
  });

  it('is not sour', () => {
    expect(myBeverage.sour).toBeFalsy();
  });
});

to compartmentalize our tests with describe, which we create with it.

We call describe to create a test module by calling it with a callback.

And we call it inside the callback to create individual tests.

expect is run in tests to check if the code being tested returns the expected result.

Conclusion

The difference between describe and it in Jest is that describe lets us divide our test suite into sections.

it is called to create individual tests which is used in the describe callback.

Categories
JavaScript Answers

How to make a mock throw an error in Jest?

Sometimes, we want to make a mock throw an error in Jest.

In this article, we’ll look at how to make a mock throw an error in Jest.

How to make a mock throw an error in Jest?

To make a mock throw an error in Jest, we can call mockImplementation with a function that throws an error.

For instance, we write:

yourMockInstance.mockImplementation(() => {
  throw new Error();
});

to use throw to thrown an error in the mocked implementation of yourMockInstance.

If we’re mocking async functions, we can use mockRejectedValue to mock the value of a rejected promise returned by the async function.

For instance, we write

test('async test', async () => {
  const yourMockFn = jest.fn().mockRejectedValue(new Error('Async error'));

  await yourMockFn();
});

then we should see 'Async error' as the promise rejection message when we call yourMockFn.

Conclusion

To make a mock throw an error in Jest, we can call mockImplementation with a function that throws an error.

Categories
JavaScript Answers

How to get the arguments called in a Jest mock function?

Sometimes, we want to get the arguments called in a Jest mock function.

In this article, we’ll look at how to get the arguments called in a Jest mock function.

How to get the arguments called in a Jest mock function?

To get the arguments called in a Jest mock function, we can use the toHaveBeenCalledWith method to check what a mocked function is called with.

For instance, we write

expect(mockedFunction).toHaveBeenCalledWith("foo", "bar");

to check the mockedFunction is called with 'foo' and 'bar' with toHaveBeenCalledWith.

Conclusion

To get the arguments called in a Jest mock function, we can use the toHaveBeenCalledWith method to check what a mocked function is called with.

Categories
JavaScript Answers

How to fix the SecurityError: localStorage is not available for opaque origins error with Jest?

Sometimes, we want to fix the SecurityError: localStorage is not available for opaque origins error with Jest.

In this article, we’ll look at how to fix the SecurityError: localStorage is not available for opaque origins error with Jest.

How to fix the SecurityError: localStorage is not available for opaque origins error with Jest?

To fix the SecurityError: localStorage is not available for opaque origins error with Jest, we can change our Jest config.

For instance, we add

"jest": {
  "verbose": true,
  "testURL": "http://localhost/"
}

to set testURL to the URL of the app being tested.

If we have multiple projects being tested, we write

module.exports = {
  verbose: true,

  projects: [{
    runner: 'jest-runner',
    testURL: "http://localhost/",

    // ...
  }]
}

to set the testURL for each project in projects to the URL of the app being tested.

Conclusion

To fix the SecurityError: localStorage is not available for opaque origins error with Jest, we can change our Jest config.