Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do you mock internal functions in TypeScript when using dependency injection
    TypeScript Jest dependency injection mock functions unit testing TypeScript testing Jest mock functions


How do you mock internal functions in TypeScript when using dependency injection


To mock internal functions in TypeScript when using dependency injection, you can follow these steps:

1. Use a generic mock function: Create a mock function that matches the signature of the internal function you want to mock, including any generic type parameters.

typescript
const myInternalFunctionMock = jest.fn().mockImplementation<
  <T, U>(arg1: T, arg2: U) => { /* mock implementation */ }
>();

2. Replace the internal function with the mock: In the class or module that contains the internal function, replace the implementation with the mock function.

typescript
class DependencyClass {
  internalFunction<T, U>(arg1: T, arg2: U): { /* return type */ } {
    return myInternalFunctionMock<T, U>(arg1, arg2);
  }
}

3. Inject the mocked dependency: In the class or module that depends on the internal function, inject an instance of the mocked dependency class.

typescript
class ClassUnderTest {
  constructor(private dependencyClass: DependencyClass) {}

  methodCallingInternalFunction() {
    return this.dependencyClass.internalFunction('hello', 42);
  }
}

4. Set expectations on the mocked function: In your tests, set expectations on the mocked internal function and assert the behavior of the class under test.

typescript
test('should call the internal function', () => {
  const mockedDependencyClass = {
    internalFunction: myInternalFunctionMock,
  };

  const classUnderTest = new ClassUnderTest(mockedDependencyClass);
  const result = classUnderTest.methodCallingInternalFunction();

  expect(myInternalFunctionMock).toHaveBeenCalledWith('hello', 42);
  // Assert other expectations on the result
});

By following these steps, you can effectively mock internal functions in TypeScript when using dependency injection:

1. Create a generic mock function for the internal function.
2. Replace the internal function implementation with the mock.
3. Inject the mocked dependency into the class under test.
4. Set expectations on the mocked function and assert the behavior of the class under test.

This approach allows you to test the class under test in isolation, without relying on the actual implementation of the internal function within the dependency class.

Citations:
[1] https://domenicoluciani.com/2022/06/17/how-to-mock-with-jest-typescript.html
[2] https://instil.co/blog/typescript-testing-tips-mocking-functions-with-jest/
[3] https://www.abrahamberg.com/blog/how-to-use-jest-in-typescript-to-mock-a-class/
[4] https://stackoverflow.com/questions/77705964/mocking-a-class-dependency-in-jest-with-typescript
[5] https://stackoverflow.com/questions/48759035/mock-dependency-in-jest-with-typescript