ink-testing-library icon indicating copy to clipboard operation
ink-testing-library copied to clipboard

Added a createRender wrapper function to allow import mocking of ink

Open danrspencer opened this issue 5 years ago • 4 comments

The current structure of ink-testing-library means that it's not possible to use something like Jest's import mocking.

e.g.

jest.mock("ink", () => {
  const inkTesting = require("ink-testing-library");

  return { render: inkTesting.render };
});

Won't work because ink-testing-library tries to import the render function from ink... which is now mocked.

This change allows a solution to this, e.g.

jest.mock("ink", () => {
  const inkTesting = require("ink-testing-library");
  const { render: realRender } = jest.requireActual("ink");

  return { render: inkTesting.createRender(realRender) };
});

Now anywhere the render function from ink is used it is replaced with the one from ink-testing-library but ink-testing-library itself still gets the real render function.

The motivation for this is to allow me to test from the outside of the app, without changing the interface of my code just to support the tests.

e.g.

import React from "react";
import { render } from "ink";

import Config from "./Config" 

export default async prog => {
  prog
    .command("config show", "Show your local config")
    .action(() => render(<Config />));
}

Can not be tested without changing the interface.

danrspencer avatar Apr 02 '19 07:04 danrspencer

Sorry for late response, was on vacation. Will check it out in a bit and get back to you.

vadimdemedes avatar Apr 09 '19 23:04 vadimdemedes

Makes sense to me. Could you document this in the readme?

vadimdemedes avatar Apr 15 '19 03:04 vadimdemedes

Added a description to the readme. Hopefully it makes sense, it feels difficult to actually explain!

danrspencer avatar Apr 17 '19 13:04 danrspencer

Hm, I find the description in the readme more confusing than the one here in your PR's description :) Would you be able to adapt it slightly and use that instead? Perhaps creating a separate section called "Testing with Jest" might simplify the explanation by focusing on Jest exclusively.

vadimdemedes avatar Apr 21 '19 20:04 vadimdemedes

Closing for lack of activity.

sindresorhus avatar May 22 '24 10:05 sindresorhus