【问题标题】:How to mock axios dependency using mocha in TypeScript?如何在 TypeScript 中使用 mocha 模拟 axios 依赖项?
【发布时间】:2020-12-03 20:13:39
【问题描述】:

这是我的示例 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 },
    });

我想使用 mocha 在 spec/test.ts 文件中编写我的测试用例。有人可以告诉我如何为 axios 依赖项创建一个模拟和存根。

【问题讨论】:

  • moxios 有帮助吗?
  • 不,我想改用依赖注入和mocha。
  • 你需要一个像sinonjs这样的模拟/存根库。如果您不想使用任何额外的软件包。像function main(httpClient) {} 这样重构您的代码,而不是使用import,然后您可以创建您的模拟httpClient 并将其传递给main 函数。

标签: javascript node.js typescript unit-testing mocha.js


【解决方案1】:

对于typestript中的模拟/存根axios,我推荐axios-mock-adapter,对于expect函数chai

这是一个如何做到这一点的例子

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();
    });
});

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 2023-03-12
    • 2018-07-23
    • 1970-01-01
    • 2016-04-22
    • 2020-10-17
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多