Eui: mocking htmlIdGenerator doesn't seem to work

Created on 9 Feb 2021  路  5Comments  路  Source: elastic/eui

I tried to mock the generator to accomplish this but couldn't get it to work.

I would have provided an codesandbox example but the jest.mock is not yet supported.

import { render, screen } from "@testing-library/react";
import * as jest from "jest";
import { EuiFormRow, EuiFlexItem, EuiTextArea } from "@elastic/eui";

it("Renders OK", async () => {
  jest.mock("@elastic/eui", () => ({
    htmlIdGenerator: jest.fn(() => () => "constant_id")
  }));

  render(
    <EuiFlexItem>
      <EuiFormRow>
        <EuiTextArea label="ss"></EuiTextArea>
      </EuiFormRow>
    </EuiFlexItem>
  );
  screen.debug(); // you can see on the console the generated ids are still random
  // expect(component).toMatchSnapshot();
});

Most helpful comment

Created an new project with only the necessary dependencies, the snippet provided by @thompsongl works for me. I did adjust:

  • added React import (I assume you're using the new auto React import preset)
  • removed the jest import, neither import jest from and import * as jest from ran for me

One other thing you can try is changing the lib directory in the mock to es or testenv. The right target depends on the rest of your environment configuration.

Screen Shot 2021-02-09 at 11 36 44 AM

All 5 comments

Try this instead:

jest.mock("@elastic/eui/lib/services/accessibility/html_id_generator", () => ({
  htmlIdGenerator: () => () => "constant_id"
}));

10x, I already tried it, also not working.

Created an new project with only the necessary dependencies, the snippet provided by @thompsongl works for me. I did adjust:

  • added React import (I assume you're using the new auto React import preset)
  • removed the jest import, neither import jest from and import * as jest from ran for me

One other thing you can try is changing the lib directory in the mock to es or testenv. The right target depends on the rest of your environment configuration.

Screen Shot 2021-02-09 at 11 36 44 AM

Awesome! The issue was I had the mock action inside my test.
When moving it outside of it (also outside of any "descibe" block) and using your full path mock action, it works.
any idea why it should be outside? anyway, you can close it thanks!

Jest moves the jest.mock calls above the imports (which are transpiled to require), as it needs the mocking information prior to resolving the other files. When jest.mock is not top-level, it isn't hoisted above the imports. Sometimes that works, but is usually not the desired functionality.

Was this page helpful?
0 / 5 - 0 ratings