Viny Machado
Viny Machado

Reputation: 629

Typescript with Jest. Mock just one named export from module

I'm having some trouble trying to mock just one named export from the module. Let's suppose we have the following named export getA, getB and getC. I just want to mock for one specific scenario the export named getA.

export const getA = () => "a"
export const getB = () => "b"
export const getC = () => "c"

Now on my test...

import {getA, getB, getC} from '../test.ts'

....

For one of my scenarios, I need to make getA returns something else but the rest of the named exports should not change.

Upvotes: 1

Views: 1736

Answers (1)

hoangdv
hoangdv

Reputation: 16157

If you only want to mock getA, you can use jest mock factory to overwrite getA as mocked function, another named exports keep the original logic.

import { getA, getB, getC } from '../test';

jest.mock('../test', () => {
  const origin = jest.requireActual('../test');
  return {
    ...origin,
    getA: jest.fn(),
  }
})

describe("getA", () => {
  test('should return new value', () => {
    (getA as jest.Mock).mockReturnValue('AAA');
    expect(getA()).toEqual('AAA');
  });
});

Upvotes: 2

Related Questions