Sure, here's an example of mocking an asynchronous function in TypeScript using Jest:
typescript
// myModule.ts
export class MyClass {
async fetchData(): Promise<string> {
// Asynchronous implementation
return await this.makeApiCall();
}
private async makeApiCall(): Promise<string> {
// Asynchronous API call implementation
return 'data from API';
}
}
// myModule.test.ts
import { MyClass } from './myModule';
import * as jest from 'jest';
describe('MyClass', () => {
let myClassInstance: MyClass;
beforeEach(() => {
myClassInstance = new MyClass();
});
afterEach(() => {
jest.clearAllMocks();
});
test('should fetch data successfully', async () => {
// Mock the private makeApiCall method
jest.spyOn(myClassInstance, 'makeApiCall').mockResolvedValue('mocked data');
const result = await myClassInstance.fetchData();
expect(result).toBe('mocked data');
expect(myClassInstance.makeApiCall).toHaveBeenCalled();
});
test('should handle error in fetchData', async () => {
// Mock the private makeApiCall method to reject with an error
jest.spyOn(myClassInstance, 'makeApiCall').mockRejectedValue(new Error('API error'));
await expect(myClassInstance.fetchData()).rejects.toThrow('API error');
expect(myClassInstance.makeApiCall).toHaveBeenCalled();
});
});
In this example, we have a `MyClass` that has an asynchronous `fetchData` method, which in turn calls a private `makeApiCall` method.
In the test suite, we use the following techniques to mock the asynchronous behavior:
1. Mocking the private method: We use `jest.spyOn` to create a spy on the `makeApiCall` method and replace its implementation with a mocked version.
2. Mocking successful response: In the first test, we use `mockResolvedValue` to set the resolved value of the mocked `makeApiCall` method to `'mocked data'`.
3. Mocking error response: In the second test, we use `mockRejectedValue` to set the rejected value of the mocked `makeApiCall` method to a new `Error` instance with the message `'API error'`.
In the tests, we then call the `fetchData` method and assert the expected behavior:
- In the first test, we expect the `fetchData` method to return the mocked data and verify that the `makeApiCall` method was called.
- In the second test, we expect the `fetchData` method to reject with the mocked error and verify that the `makeApiCall` method was called.
Finally, we use the `afterEach` hook to clear all mocks after each test to ensure a clean state for the next test.
By using these techniques, you can effectively mock asynchronous functions in TypeScript when using Jest as your testing framework.