【问题标题】:Verify request with axios-mock-adapter?使用 axios-mock-adapter 验证请求?
【发布时间】:2021-08-26 17:46:30
【问题描述】:

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

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

}

【问题讨论】:

  • 可以给我getPublications的代码吗?
  • 刚刚更新了我的问题

标签: javascript reactjs jestjs axios axios-mock-adapter


【解决方案1】:

在您提供的测试代码中,您正在监视 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) })
}

【讨论】:

    【解决方案2】:

    我不习惯在我的测试中使用jest.spy,但我认为您可以尝试以下方法:

    import axios from 'axios';
    
    jest.mock('axios');
    ...
    
    it('gets publications', async() => {
    
        const get = axios.get.mockResolvedValueOnce(yourMockedData)
    
        let queryParameters = {
            operation: 'FSale'
        }
    
    
        const publications = await PublicationService.getPublications(queryParameters);
    
        expect(publications.data.answer.publications).toEqual([ "pub1", "pub2", "pub3" ]); // works fine
        expect(get).toHaveBeenCalled(); //This fails
    })
    

    【讨论】:

    • 感谢您的回答,但我希望继续使用 axios-mock-adapter。
    • 好吧,只是想知道你是否尝试过使用 Promise 而不是 async await
    • @Stackoverflowed 在另一边,我宁愿对 PublicationService 模拟 axios 进行单独测试,然后在此测试中对 PublicationService 使用模拟响应。这个想法是没有依赖关系。
    【解决方案3】:

    您可以使用https://github.com/ctimmerm/axios-mock-adapter#history 功能检查实际调用了哪些内容,并对 URL、标头、方法和其他内容进行断言。

    【讨论】:

      猜你喜欢
      • 2018-06-13
      • 2018-03-17
      • 2019-03-31
      • 2018-04-07
      • 2018-12-18
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      相关资源
      最近更新 更多