Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock an exported array with Jest?

I want to mock an array that's being exported in a TypeScript file. How can I do this with Jest?

I have file like:

// names.ts
export const names = ['Alice', 'Bob'];

Which is used like:

// get-names.ts
import names from './names';

export const getNames = () => { return names };

How can I mock this array in Jest?

What I want to do is something like:

// get-names.test.ts
import { getNames } from './get-names';

const mockedModule = jest.createMockFromModule('./names');

describe('get names', () => {
  it('gets the list of names', () => {
    mockedModule.names = ['Carol', 'Dave'];
    expect(getNames()).toEqual(['Carol', 'Dave']);
  });
});
like image 563
Stewart Avatar asked Oct 22 '25 04:10

Stewart


1 Answers

You could use dynamic imports alongside doMock to mock a module for each test:

// names.ts
export const names = ["Alice", "Bob"];

Make sure you fix your import statement for names:

// get-names.ts
import { names } from "./names";

export const getNames = () => {
  return names;
};

The test file:

// get-names.test.ts
describe("get names", () => {
  beforeEach(() => {
    jest.resetModules();
  });

  it("gets the list of names", async () => {
    jest.doMock("./names", () => ({
      __esModule: true,
      names: ["Carol", "Dave"],
    }));
    const { getNames } = await import("./get-names");
    expect(getNames()).toEqual(["Carol", "Dave"]);
  });
});
like image 193
JohannCooper Avatar answered Oct 23 '25 18:10

JohannCooper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!