简体   繁体   English

模拟APi称笑话

[英]Mocking APi calls jest

I have a DataService which is responsible for my API calls - I am trying to mock the api call in jest but it does not seem to be working. 我有一个DataService负责我的API调用-我试图开玩笑地模拟api调用,但似乎无法正常工作。 I am not sure what I am doing wrong - my DataService seems to be undefined. 我不确定自己在做什么错-我的DataService似乎未定义。

Here is the function 这是功能

const getStepData = (id) => {
  return async dispatch => {
    try {
      dispatch(fetchStepBegin());

      const res = await DataService.fetchStepData(id);
      const sortedTask = sortedTaskData(res)

      const sortedStepData = sortStepData(res)
      const newData = createSortedDataForDragAndDrop(sortedTask, sortedStepData)
      dispatch(fetchRawStepDataSuccess(res.data))
      dispatch(fetchStepDataSuccess(newData))
    }
    catch (err) {
      dispatch(fetchStepError(err))
      throw (err)
    }
  }
}

Here is the test that I have written - I am pretty sure I am mocking incorrectly 这是我编写的测试-我很确定自己在嘲笑不正确

  it('Data Api end point called with corrent studyId', () => {
    jest.mock(DataService);
    DataService.fetchStepData() = jest.fn()
    CellStepManagementOperations.getStepData(5);
    expect(DataService.fetchStepData).toHaveBeenCalledWith(5);

  });

I think the problem here is that you are trying to test asynchronous action creators, synchronously . 我认为这里的问题是您正在尝试同步测试异步操作创建者。 So your expect function doesn't wait for your getStepData to finish before running. 因此,您的expect函数不会在运行之前等待getStepData完成。

I've had to something very similar to what you're trying to do and I used a library called redux-testkit . 我必须要做的事情与您尝试做的事情非常相似,并且我使用了一个名为redux-testkit的库。 Please see the part about testing async action creators with services here . 请在此处查看有关使用服务测试异步操作创建者的部分。 You can even set mock return values for your API services which I've found very helpful when testing. 您甚至可以为API服务设置模拟返回值,在测试时,我发现这非常有用。

Using this library, you will be able to await for your getStepData async action creator to complete before running your expect function. 使用此库,您将能够await getStepData异步操作创建者完成运行expect函数之前的操作。

You will have to play around with your code but it might look something like this: 您将不得不使用您的代码,但是它可能看起来像这样:

it('Data Api end point called with corrent studyId', () => {
  jest.mock(DataService);
  DataService.fetchStepData() = jest.fn()
  const dispatches = await Thunk(CellStepManagementOperations.getStepData).execute(5);
  expect(DataService.fetchStepData).toHaveBeenCalledWith(5);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM