gpt4 book ai didi

javascript - 使用 axios-mock-adapter 验证请求?

转载 作者:行者123 更新时间:2023-12-02 21:58:00 25 4
gpt4 key购买 nike

我使用来自axios-mock-adapter的MockAdapter进行了以下测试。不过,我试图断言 get 函数已被有效调用,因此我创建了一个 spy 。由于某种原因,它似乎不起作用,我得到:

expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls: 0

这是我的测试:

it('gets publications', async() => {

let spy = jest.spyOn(axios, "get");
var mock = new MockAdapter(axios);
mock.onGet(PUBLICATIONS_PATH + '/publications').reply(200,
{
answer: {
publications: [ "pub1", "pub2", "pub3" ]
}
});

let queryParameters = {
operation: 'FSale'
}


const publications = await PublicationService.getPublications(queryParameters);

expect(publications.data.answer.publications).toEqual([ "pub1", "pub2", "pub3" ]); // works fine
expect(spy).toHaveBeenCalled(); //This fails
})

我实际上正在尝试使用该方法 answered here

更新:这是 getPublications 的代码

async function _getPublications(queryParameters){
return await axios({
method: 'get',
url: `${PUBLICATIONS_PATH}/publications`,
cancelToken: CancelTokenService.getSource().token,
params: queryParameters,
headers: {
authorization: LocalStorageService.getAuthorization(),
'Accept': ResourcesVersions.PUBLICATION
}
}).then(function (response){ return response }).catch(function (error){ return (axios.isCancel(error) ? error : error.response) })

}

最佳答案

在您提供的测试代码中,您正在监视 axios get 方法,但在 getPublications 方法中,您没有调用该方法。相反,您直接调用 axios 方法。

由于监视 axios 默认方法并不容易,我建议更改 getPublications 中的代码以使用 get 方法:

async function _getPublications(queryParameters){
return await axios.get(`${PUBLICATIONS_PATH}/publications`, {
cancelToken: CancelTokenService.getSource().token,
params: queryParameters,
headers: {
authorization: LocalStorageService.getAuthorization(),
'Accept': ResourcesVersions.PUBLICATION
}
}).then(function (response){ return response }).catch(function (error){ return (axios.isCancel(error) ? error : error.response) })
}

关于javascript - 使用 axios-mock-adapter 验证请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59955458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com