5

Here is my sample src/main.ts file

import axios from 'axios';
export async function main() {
     const URL = 'test url';
     const secretKey = 'Test key'
     const response = await axios.get(URL, {
        headers: { 'Content-Type': 'application/json', 'KEY': secretKey },
    });

I want to write my test case in spec/test.ts file using mocha. Can someone show me how to create a mock and stub for axios dependency.

3
  • 1
    does moxios help? Commented Aug 14, 2020 at 3:56
  • 1
    Nope, I want to use dependency injection and mocha instead. Commented Aug 14, 2020 at 16:42
  • You need a mock/stub library like sinonjs. If you don't want to use any extra package. Refactor your code like function main(httpClient) {} instead of using import, then you can create your mocked httpClient and pass it to main function. Commented Aug 16, 2020 at 5:33

1 Answer 1

6

For mock/stub axios in typestript I recommend axios-mock-adapter, for expect functions chai

Here is an example of how to do this

request.ts

import axios from 'axios';

const apiConfig = {
    returnRejectedPromiseOnError: true,
    timeout: 30000,
    headers: {
        common: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
    },
};

const request = axios.create(apiConfig);
export default request;

main.ts

import request from './request';

export const URL = 'https://httpbin.org/get';
export const secretKey = 'secret_key';

export async function main() {

    const response = await request.get(URL, {
        headers: {
            KEY: secretKey,
        },
    });

    // response logic

    return response;
}

main.spec.ts

import MockAdapter from 'axios-mock-adapter';
import { expect } from 'chai';

import request from './request';
import { main, URL, secretKey } from './main';


describe('Request test', () => {
    let stub: MockAdapter;
    const receivedData = { data: 'data' };

    before(() => {
        stub = new MockAdapter(request);
        stub.onGet(URL, {
            headers: {
                KEY: secretKey,
            },
        }).replyOnce(200, receivedData);
        // replyOnce if you assume that your code sends a single request
    });

    it('test', async () => {
        const response = await main();

        expect(response.status).to.be.equal(200);
        expect(response.data).to.be.deep.equal(receivedData);
    });

    after(() => {
        stub.restore();
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.