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']);
});
});
CodePudding user response:
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"]);
});
});
CodePudding user response:
Here's how I would do it:
// get-names.test.ts
import { getNames } from "./get-names";
import { names } from "./names";
jest.mock("./names", () => ({
__esModule: true,
names: []
}));
describe("names", () => {
beforeEach(() => {
// reset (wipe) mocked array
names.splice(0, names.length);
});
it("gets the list of names", () => {
names.push(...["Carol", "Dave"]);
expect(getNames()).toEqual(["Carol", "Dave"]);
});
it("gets the list of more names", () => {
names.push(...["Enid", "Fred"]);
expect(getNames()).toEqual(["Enid", "Fred"]);
});
});
Basically:
- mock
./names
- import
./names
- empty the array in a
beforeEach
- populate the array in each test
Try the codesandbox: https://codesandbox.io/s/confident-sea-71fig3?file=/src/get-names.test.ts:0-561