Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you mock asynchronous functions with async/await syntax in TypeScript without using Jest


Can you mock asynchronous functions with async/await syntax in TypeScript without using Jest


Yes, you can mock asynchronous functions with async/await syntax in TypeScript without using Jest. One way to do this is by using a library like Sinon.js, which provides a more flexible mocking solution compared to the built-in mocking capabilities of Jest.

Here's an example of how you can mock an asynchronous function using Sinon.js in TypeScript:

typescript
import * as sinon from 'sinon';

// myModule.ts
export async function fetchData(): Promise<string> {
  // Asynchronous implementation
  return await makeApiCall();
}

private async makeApiCall(): Promise<string> {
  // Asynchronous API call implementation
  return 'data from API';
}

// myModule.test.ts
import { fetchData, makeApiCall } from './myModule';
import * as sinon from 'sinon';

describe('fetchData', () => {
  let sandbox: sinon.SinonSandbox;

  beforeEach(() => {
    sandbox = sinon.createSandbox();
  });

  afterEach(() => {
    sandbox.restore();
  });

  test('should fetch data successfully', async () => {
    // Mock the private makeApiCall method
    const mockedMakeApiCall = sandbox.stub(this, 'makeApiCall').resolves('mocked data');

    const result = await fetchData();
    expect(result).toBe('mocked data');
    expect(mockedMakeApiCall).to.have.been.called;
  });

  test('should handle error in fetchData', async () => {
    // Mock the private makeApiCall method to reject with an error
    const mockedMakeApiCall = sandbox.stub(this, 'makeApiCall').rejects(new Error('API error'));

    await expect(fetchData()).rejects.toThrow('API error');
    expect(mockedMakeApiCall).to.have.been.called;
  });
});

In this example, we use Sinon.js to create a sandbox and mock the `makeApiCall` method. The `sandbox.stub()` method allows us to create a stub for the `makeApiCall` method and control its behavior.

The key points are:

1. Create a Sinon.js sandbox using `sinon.createSandbox()`.
2. Use `sandbox.stub()` to create a stub for the asynchronous function you want to mock.
3. Use the `resolves()` or `rejects()` methods to set the resolved or rejected value of the mocked function.
4. Verify the behavior of the `fetchData` function by asserting the result or the expected error.
5. Restore the sandbox after each test using `sandbox.restore()`.

By using Sinon.js, you can effectively mock asynchronous functions with async/await syntax in TypeScript without relying on the built-in mocking capabilities of Jest. This approach provides more flexibility and control over the mocking behavior, which can be useful in certain scenarios.

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.benmvp.com/blog/using-jest-mock-functions-typescript/
[4] https://www.salto.io/blog-posts/typescript-unit-testing-pitfalls-with-jest-and-how-to-work-around-them
[5] https://dev.to/viglioni/mocking-dependencies-with-jest-typescript-12im