简体   繁体   English

如何在 TypeScript 中使用 mocha 模拟 axios 依赖项?

[英]How to mock axios dependency using mocha in TypeScript?

Here is my sample src/main.ts file这是我的示例 src/main.ts 文件

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.我想使用 mocha 在 spec/test.ts 文件中编写我的测试用例。 Can someone show me how to create a mock and stub for axios dependency.有人可以告诉我如何为 axios 依赖项创建一个模拟和存根。

For mock/stub axios in typestript I recommend axios-mock-adapter , for expect functions chai对于typestript中的模拟/存根axios,我推荐axios-mock-adapter ,对于期望函数chai

Here is an example of how to do this这是如何执行此操作的示例

request.ts请求.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 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 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();
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM