Categories
JavaScript Answers

How to change mock implementation for a single test with Jest?

Sometimes, we want to change mock implementation for a single test with Jest.

In this article, we’ll look at how to change mock implementation for a single test with Jest.

How to change mock implementation for a single test with Jest?

To change mock implementation for a single test with Jest, we can call the mockImplementation method on the function we want to mock in our test.

For instance, we write

import {
  funcToMock
} from './module';
jest.mock('./module');

beforeEach(() => {
  funcToMock.mockImplementation(() => {
    /* default implementation */
  });
});

test('with new mock function', () => {
  funcToMock.mockImplementation(() => {
    /* implementation specific to this test */
  });
  // ...
});

to call funcToMock.mockImplementation with the mock function as a callback to mock funcToMock in the beforeEach callback to provide a mocked version of funcToMock for all tests.

Then in the 'with new mock function' test, we call funcToMock.mockImplementation again with another function to mock the function for this specific test.

Conclusion

To change mock implementation for a single test with Jest, we can call the mockImplementation method on the function we want to mock in our test.

Categories
JavaScript Answers

How to disable console inside unit tests with Jest?

Sometimes, we want to disable console inside unit tests with Jest.

In this article, we’ll look at how to disable console inside unit tests with Jest.

How to disable console inside unit tests with Jest?

To disable console inside unit tests with Jest, we can use the silent option or disable console output in the config.

We run

jest --silent

to run tests without showing console output.

In jest setup file, we can add

global.console = {
  log: jest.fn(),
  error: console.error,
  warn: console.warn,
  info: console.info,
  debug: console.debug,
};

to replace console.log with a stubbed function by setting global.console.log to jest.fn.

The other console methods are set to the regular console methods.

Conclusion

To disable console inside unit tests with Jest, we can use the silent option or disable console output in the config.

Categories
JavaScript Answers

How to mock the JavaScript window object using Jest?

Sometimes, we want to mock the JavaScript window object using Jest.

In this article, we’ll look at how to mock the JavaScript window object using Jest.

How to mock the JavaScript window object using Jest?

To mock the JavaScript window object using Jest, we can use the jest.spyOn method.

For instance, we write

let windowSpy;

beforeEach(() => {
  windowSpy = jest.spyOn(window, "window", "get");
});

afterEach(() => {
  windowSpy.mockRestore();
});

it('should return https://example.com', () => {
  windowSpy.mockImplementation(() => ({
    location: {
      origin: "https://example.com"
    }
  }));

  expect(window.location.origin).toEqual("https://example.com");
});

to call jest.spyOn to mock the get global function in the beforeEach callback.

In the afterEach callback, we call windowSpy.mockRestore to restore window to its original state.

And then we call windowSpy.mockImplementation to mock it window.get with a function that returns location.origin.

And then we check that window.location.origin is "https://example.com".

This test should pass because of the mock.

Conclusion

To mock the JavaScript window object using Jest, we can use the jest.spyOn method.

Categories
JavaScript Answers

How to test for object keys and values with Jest?

Sometimes, we want to test for object keys and values with Jest.

In this article, we’ll look at how to test for object keys and values with Jest.

How to test for object keys and values with Jest?

To test for object keys and values with Jest, we can use the toMatchObject method.

For instance, we write:

const expected = {
  name: 'foo'
}
const actual = {
  name: 'foo',
  type: 'bar'
}
expect(actual).toMatchObject(expected)

to check if the expected.name property matches the actual.name property.

The type property is ignored in the test since type isn’t in actual.

Conclusion

To test for object keys and values with Jest, we can use the toMatchObject method.

Categories
JavaScript Answers

How to mock local storage in Jest tests?

To mock local storage in Jest tests, we can create our own mock local storage methods.

For instance, we write

const localStorageMock = (() => {
  let store = {};
  return {
    getItem(key) {
      return store[key];
    },
    setItem(key, value) {
      store[key] = value.toString();
    },
    clear() {
      store = {};
    },
    removeItem(key) {
      delete store[key];
    }
  };
})();
Object.defineProperty(window, 'localStorage', {
  value: localStorageMock
});

to create the localStorageMock object by creating an IIFE that returns an object that manipulates the store object.

It has getItem to return store[key].

setItem sets store[key] to value converted to a string.

clear sets store to an empty object.

And removeItem removes the store property with the given key with delete.

And then we attach our mocked local storage object to window with Object.defineProperty.