When working in the Gutenberg codebase, I’ve occasionally found myself needing to mock out an API to avoid making real HTTP requests within my unit tests.

In Gutenberg most API requests are routed through apiFetch from @wordpress/api-fetch which is basically just a wrapper around the browser’s native Fetch API. Therefore, by mocking apiFetch we can control HTTP requests within our Gutenberg unit tests.

Gutenberg uses Jest as it’s test framework so let’s look at how we can use it to mock out apiFetch.

Mocking apiFetch in unit tests

Firstly we need pull in the API fetch package into our test. To do this we import the default export from the @wordpress/api-fetch package.

Note, this is usually named apiFetch but you could alias it to anything you want should that be required:

import apiFetch from '@wordpress/api-fetch';

Once that is in place we can use Jest’s mocking framework to mock out the entire package implementation:

jest.mock( '@wordpress/api-fetch' );

This leaves us with apiFetch as a Jest mock function which allows us to use any of the available mock modifiers to control it’s behaviour during the test.

For example, if I wanted to force calls to apiFetch to return a particular value I could do something like this:

const data = {
  foo: "Lorem ipsum dolor",
  bar: "Lorem ipsum dolor",
  baz: "Lorem ipsum dolor",

// Here's where we control how apiFetch behaves during this test.
apiFetch.mockReturnValueOnce( Promise.resolve( data ) );

await expect(
    myFuncThatCallsApiFetch( 'https://www.some-url.com' )
).resolves.toEqual( data );

So there you have it. A very simple way to mock out @wordpress/api-fetch in your unit tests.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.