首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Moxios模拟一个函数内的多个api调用

使用Moxios模拟一个函数内的多个api调用
EN

Stack Overflow用户
提问于 2020-04-03 14:08:10
回答 1查看 185关注 0票数 3

我正在为我的服务类编写一个测试用例。我想模拟一个函数中的多个调用,因为我从一个函数进行了两个API调用。我试着跟随,但它不起作用

代码语言:javascript
复制
it('should get store info', async done => {
      const store: any = DealersAPIFixture.generateStoreInfo();
      moxios.wait(() => {
        const request = moxios.requests.mostRecent();
        request.respondWith({
          status: 200,
          response: store
        });
        const nextRequest = moxios.requests.at(1);
        nextRequest.respondWith({
          status: 200,
          response: DealersAPIFixture.generateLocation()
        });
      });
      const params = {
        dealerId: store.dealerId,
        storeId: store.storeId,
        uid: 'h0pw1p20'
      };
      return DealerServices.retrieveStoreInfo(params).then((data: IStore) => {
        const expectedOutput = DealersFixture.generateStoreInfo(data);
        expect(data).toMatchObject(expectedOutput);
      });
    });

常量nextRequest始终未定义

它抛出错误TypeError: Cannot read property 'respondWith' of undefined

这是我的服务类

代码语言:javascript
复制
static async retrieveStoreInfo(
    queryParam: IStoreQueryString
  ): Promise<IStore> {
    const res = await request(getDealerStoreParams(queryParam));
    try {
      const locationResponse = await graphQlRequest({
        query: locationQuery,
        variables: { storeId: res.data.storeId }
      });
      res.data['inventoryLocationCode'] =
        locationResponse.data?.location?.inventoryLocationCode;
    } catch (e) {
      res.data['inventoryLocationCode'] = 'N/A';
    }
    return res.data;
  }
EN

回答 1

Stack Overflow用户

发布于 2021-07-03 05:07:31

聚会迟到了,但我今天必须解决同样的问题。

我的(不理想的)解决方案是对除最后一个请求之外的每个请求使用moxios.stubRequest。此解决方案基于moxios.stubRequestmoxios.requests推送请求的事实,因此,在响应最后一个调用之后,您将能够分析所有请求。

代码看起来像这样(考虑到你有3个请求要做):

代码语言:javascript
复制
moxios.stubRequest("get-dealer-store-params", {
  status: 200,
  response: {
    name: "Audi",
    location: "Berlin",
  }
});

moxios.stubRequest("graph-ql-request", {
  status: 204,
});

moxios.wait(() => {
  const lastRequest = moxios.requests.mostRecent();
  
  lastRequest.respondWith({
    status: 200,
    response: {
      isEverythingWentFine: true,
    },
  });

  // Here you can analyze any request you want
  
  // Assert getDealerStoreParams's request
  const dealerStoreParamsRequest = moxios.requests.first();
  expect(dealerStoreParamsRequest.config.headers.Accept).toBe("application/x-www-form-urlencoded");

  // Assert graphQlRequest
  const graphQlRequest = moxios.requests.get("POST", "graph-ql-request");
  ...

  // Assert last request
  expect(lastRequest.config.url).toBe("status");
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61005974

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档