Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can you mock asynchronous functions in TypeScript


How can you mock asynchronous functions in TypeScript


To mock asynchronous functions in TypeScript, you can follow these steps:

1. Use `jest.fn().mockImplementation()`:
- Create a mock function using `jest.fn()`.
- Use the `mockImplementation()` method to provide an asynchronous implementation for the mock function.

typescript
   const myAsyncFunction = jest.fn().mockImplementation(async () => {
     // Asynchronous mock implementation
     return 'mocked result';
   });
   

2. Use `jest.fn().mockResolvedValue()`:
- Create a mock function using `jest.fn()`.
- Use the `mockResolvedValue()` method to set the resolved value for the mock function.

typescript
   const myAsyncFunction = jest.fn().mockResolvedValue('mocked result');
   

3. Use `jest.fn().mockRejectedValue()`:
- Create a mock function using `jest.fn()`.
- Use the `mockRejectedValue()` method to set the rejected value for the mock function.

typescript
   const myAsyncFunction = jest.fn().mockRejectedValue(new Error('mocked error'));
   

4. Verify the mock function's behavior:
- In your tests, call the mocked asynchronous function and assert the expected behavior.

typescript
   test('mocks asynchronous function', async () => {
     const result = await myAsyncFunction();
     expect(result).toBe('mocked result');
     expect(myAsyncFunction).toHaveBeenCalled();
   });
   

By using these methods, you can effectively mock asynchronous functions in TypeScript and ensure that your tests cover the expected behavior, including error cases.

Remember to clean up the mocks after each test using `jest.clearAllMocks()` or `afterEach(() => jest.clearAllMocks())` to maintain a clean test environment.

Citations:
[1] https://instil.co/blog/typescript-testing-tips-mocking-functions-with-jest/
[2] https://domenicoluciani.com/2022/06/17/how-to-mock-with-jest-typescript.html
[3] https://www.benmvp.com/blog/using-jest-mock-functions-typescript/
[4] https://www.reddit.com/r/typescript/comments/184de6g/making_tests_bearable_in_typescript/
[5] https://www.salto.io/blog-posts/typescript-unit-testing-pitfalls-with-jest-and-how-to-work-around-them