有API测试

问题描述 投票:-1回答:1

我在应用程序的API层上编写了许多单元测试,但我在使用jest来模拟各种端点时遇到了麻烦。我没有这方面的经验,很多文章都没有帮助我的具体情况

我有特定的模块设置,使用Axios发出请求。这是我需要模拟的特定调用:

export async function ajax<T>(options: AxiosRequestConfig): Promise<T> {
    options.baseURL = ApiConfig.currentContext.ApiPath;
    options.headers = options.headers || {};
    options.headers['Accept-Language'] = Locale.resolveCulture();
    options.withCredentials = true;

    try {
        const response = await AXIOS_ADAPTER(options);

        return response.data;
    }
    catch (error) {
        throw new ApiError(error);
    }
}

以下是我目前的测试结果:

import * as http from '../src/http';

import { account } from '../src/api/account';


describe('Account Credit Cards Test Suite', () => {
    it('should get all saved credit cards in an account', async () => {
       const spy = jest.spyOn(http, 'ajax');
       const getAll = await account.creditCards.getAll();

       expect(spy).toHaveBeenCalled();
       expect(getAll).toBe(true);
    });
});

这是一个初步的测试,看看我是否能让它工作,但不幸的是,resolveCulture调用依赖于window对象,因为它是一个Web应用程序。

我的问题是如何模拟ajax调用,以便我可以看到params传递给它的是什么,以便断言请求的行为符合预期。

javascript ajax testing jestjs
1个回答
0
投票

如果您使用axios进行api通话。您可以使用axios-mock-adapter npm模块来模拟api调用。看一下我使用Jest和axios-mock-adapter测试axios api调用的下面的链接。

https://codesandbox.io/s/5vq2qv67on

https://github.com/ctimmerm/axios-mock-adapter

© www.soinside.com 2019 - 2024. All rights reserved.