Stubbing a React component is easy with Sinon. You can replace a component with a Sinon stub which is rendered as a child in the component under tests.

Here is an example of stubbing a component:

import React from "react";
import { render } from "@testing-library/react";
import "jest-dom/extend-expect";

import sinon from "sinon";
import * as ToStubComponent from "./to-stub-component";
import { App } from "./app";

describe("Sinon stub", function() {
  beforeAll(function() {
    sinon.stub(ToStubComponent, "default").returns(<div>A stub</div>);
  });

  it("basic React components", function() {
    const { container } = render(<App />);

    expect(container).toHaveTextContent("A stub");
  });
});

Sinon React component stub code sandbox for you to try out.

Error to look out for

default(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

Importing the component to stub and stubbing it in the before hook.

Example code that causes the above error:

import sinon from 'sinon';
import * as ToStubComponent from './to-stub-component';

describe('....', function () {
  before(function(){
    ...
    sinon.stub(ToStubComponent, 'default').returns(<div/>);
    ...
  });
  it('my test', ...);
});

Solution

The issue from what I can tell is React is trying to execute the component as a class component and there is no render method available. This can be solved by stubbing as a string.

sinon.stub(ToStubComponent, 'default').value('div');