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']);
});
});
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"]);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With