Jest.js 你怎么能在不嘲笑整个图书馆的情况下用笑话监视axios?

q1qsirdb  于 11个月前  发布在  Jest
关注(0)|答案(2)|浏览(146)

本质上,我试图知道在这个例子中,axios是否被正确的args调用:

import HttpRequestMock from 'http-request-mock';
import axios, { AxiosPromise } from 'axios';

const url = 'https://example.com';

// myFile.ts
// Private function that isn't exposed
async function businessLogic(): Promise<AxiosPromise<unknown>> {
  return axios({  // How do I know this has been called from jest?
    method: 'put',
    url,
  });
}

export async function myCoolEndpoint(): Promise<void> {
  const res = await businessLogic();
  console.log(res.data);
}

个字符
我一直无法找到任何人能够窥探axios时,它是这样叫,而不是嘲笑了整个图书馆。

h9a6wy2h

h9a6wy2h1#

为了实现所需的行为,您应该对代码进行以下更改:
axios({ method: 'put',url})替换为axios.request({ method: 'put',url})
expect(spy).toHaveBeenCalled();替换为expect(axios.request).toHaveBeenCalled();
您不必保存spyOn方法的返回
希望它能帮助

iaqfqrcu

iaqfqrcu2#

我通常会为http方法创建一个 Package 器文件,你可以在其中重用http代码,比如:

export function httpPut<T = any, R = any>(
  url: string,
  data: T,
): Promise<AxiosResponse<R>> {
  return axios({
    method: 'put',
    url,
    data: data,
  })
}

export function httpGet<R = any>(
  url: string
): Promise<AxiosResponse<R>> {
  return axios({
    method: 'get',
    url,
  })
}

// and so on

字符串
然后在我的jest文件中模拟http Package 器函数

describe('test suite', () => {
  const httpMock: any = {}

  beforeEach(() => {
    jest.resetModules()
    jest.doMock('../path/to/wrapper/httpFile', () => httpMock)
  })

  it('test you http call', async () => {
    // set up the expected response 
    httpMock.httpPut = jest.fn(() => [
      { status: 200, data: { /* expected response */ }, /* any more axios stuff */ },
    ])

    await myCoolEndpoint();

    expect(httpMock.httpPut).toBeCalledTimes(1);
    expect(httpMock.httpPut).toBeCalledWith(/* expected params */);
  })
})


这样,您就不会模拟整个axios库,而只是模拟http Package 器函数,您可以抛出不同的错误,并查看函数的行为
希望这对你有帮助,干杯

相关问题