- Newest
- Most votes
- Most comments
For implementing above scenario you can use a dedicated mocking library like axios-mock-adapter used for testing applications that use the axios HTTP client library in below format as mentioned in the example:
- Import axios-mock-adapter and create a new instance, passing the axios module as an argument.
- Use the onPost method to define the mock response for the specific URL or request body.
Here's an example:
import MockAdapter from 'axios-mock-adapter';
describe('test service', () => {
let mock;
beforeEach(() => {
mock = new MockAdapter(axios);
mock.onPost(path).reply(200, { message: 'success' });
});
afterEach(() => {
mock.restore();
});
it('should mock axios instance.post', async () => {
await handler(event);
expect(mock.history.post[0].headers).toEqual(
expect.objectContaining({
'Content-type': 'application/json',
Authorization: expect.stringMatching(/^Bearer .+$/),
})
);
});
});
This approach uses axios-mock-adapter to intercept the axios.post call and define the mock response. The onPost method is used to specify the mock response for the specific request.
To effectively mock the axios instance in your Lambda function unit tests, you can use Jest's mocking capabilities. Here's an approach you can try:
- First, mock the entire axios module:
jest.mock('axios');
- In your test setup, create a mock implementation for axios.create:
const mockPost = jest.fn(); const mockAxiosCreate = jest.fn(() => ({ post: mockPost, })); (axios.create as jest.Mock).mockImplementation(mockAxiosCreate);
- Now you can set up expectations for the post method in your individual tests:
it('should mock axios instance.post', async () => { mockPost.mockResolvedValueOnce({ status: 200, data: { message: 'success' }, }); await handler(event); expect(mockPost).toHaveBeenCalledWith( expect.any(String), expect.any(Object), expect.objectContaining({ headers: expect.objectContaining({ 'Content-type': 'application/json', Authorization: expect.stringMatching(/^Bearer .+$/), }), }) ); });
This approach mocks the axios.create method to return an object with a mocked post method. You can then set up expectations for the post method in each test, allowing you to control its behavior and verify it's called correctly.
Remember to reset your mocks between tests if necessary:
beforeEach(() => { jest.clearAllMocks(); });
This method should prevent timeouts by ensuring that no real HTTP requests are made during your tests. It also gives you fine-grained control over the mock responses, allowing you to test different scenarios easily.
Sources
AWS Lambda function testing in C# - AWS Lambda
Relevant content
- asked 2 years ago
- asked 4 years ago

this did not work in my lambda axiosInstance end up with 'undefined' value