😜 mocking gatsby image

In my quest for 100% test coverage, I've had to mock some gatsby internals to get tests to run in isolation. Since the release of Gatsby v3, I had to take into account the new gatsby-plugin-image.

In order to mock the plugin, I essentially copied the original plugin and then overwrote the GatsbyImage and StaticImage components with a function. The function creates a simple React component that renders a vanilla <img> tag. This allows me to run assertions in jest tests like I would expect.

jest.mock("gatsby-plugin-image", () => {
    const React = require("react")
    const plugin = jest.requireActual("gatsby-plugin-image")

    const mockImage = ({imgClassName, ...props}) =>
        React.createElement("img", {
            className: imgClassName,

    const mockPlugin = {
        GatsbyImage: jest.fn().mockImplementation(mockImage),
        StaticImage: jest.fn().mockImplementation(mockImage),

    return mockPlugin

You can place this code snippet in your jest setup file like I did. While this mock doesn't cover all of the functionality of gatsby-plugin-image, it certainly handles the features that I use in my daily development.

Feel free to give this mock a try, and if there's enough interest I can package this up and release it on npm.