How to mock axios dependency using mocha in typescript?

by raven_corwin , in category: Javascript , 3 months ago

How to mock axios dependency using mocha in typescript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 3 months ago

@raven_corwin 

To mock Axios dependency in Mocha using TypeScript, you can use a library like sinon to create a stub for the Axios library. Here's an example of how you can mock Axios dependency in a Mocha test:

  1. Install sinon and @types/sinon package if not already installed:
1
npm install sinon @types/sinon --save-dev


  1. Create a test file with your Axios-dependent code:
1
2
3
4
5
6
import axios from 'axios';

export async function fetchData(url: string) {
  const response = await axios.get(url);
  return response.data;
}


  1. Write a Mocha test that mocks the Axios dependency:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { expect } from 'chai';
import sinon from 'sinon';
import { fetchData } from './example';

describe('fetchData', () => {
  it('should fetch data from the API', async () => {
    const mockData = { message: 'Hello, World!' };
    
    // Create a sinon stub for the axios.get method
    const axiosStub = sinon.stub(axios, 'get').resolves({ data: mockData });

    // Call the fetchData function
    const result = await fetchData('https://example.com/api');

    // Ensure that axios.get was called with the correct URL
    sinon.assert.calledWith(axiosStub, 'https://example.com/api');

    // Ensure that the result is equal to the mock data
    expect(result).to.deep.equal(mockData);

    // Restore the original axios.get method
    axiosStub.restore();
  });
});


  1. Run the test using Mocha:
1
npx mocha --require ts-node/register src/*.test.ts


This test will mock the Axios dependency using sinon and ensure that the fetchData function works correctly. Remember to restore the original method after the test to prevent any side effects.