Roman Hrybinchuk
Roman Hrybinchuk

Reputation: 187

Jest mock not exported function from another module, Typescript

I want to be able to mock function that is not exported but used in that function that I want to test. Here is the small code example.

file.ts

const hello  = () => {
    console.log('hello');
}

export const say = () =>{
    hello  ()
    return 10;
}

file.test.ts

  import {say } from 'file'; 

  describe("Test ", () => {
        it("test", async () => {
            // how to mock hello before that ? 
            say();
            
         
        })
    })

Upvotes: 1

Views: 3111

Answers (1)

somallg
somallg

Reputation: 2043

Jest has the ability to mock ES module (whole ts/js file), but with your current implementation is impossible to do so.

My suggestion is to extract function hello into another file called hello.ts and import it for function say to use. Then jest can mock the hello.ts

Sample code:

// hello.ts
export const hello  = () => {
  console.log('hello');
}
// say.ts
import { hello } from "./hello";

export const say = () =>{
  hello();
  return 10;
}
// say.test.ts
import { say } from './say';

jest.mock('./hello', () => {
  return {
    hello: jest.fn().mockImplementation(() => {
      console.log('mock hello');
    })
  };
});

describe('Test ', () => {
  it('test', async () => {
    // how to mock hello before that ?
    say();
  });
});

Output:

enter image description here

Upvotes: 3

Related Questions