4

I am writing a test case for my service class. I want to mock multiple calls inside one function as I am making two API calls from one function. I tried following but it is not working

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

const nextRequest is always undefined

it throw error TypeError: Cannot read property 'respondWith' of undefined

here is my service class

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;
  }
Jitender
  • 7,593
  • 30
  • 104
  • 210

1 Answers1

0

Late for the party, but I had to resolve this same problem just today.

My (not ideal) solution is to use moxios.stubRequest for each request except for the last one. This solution is based on the fact that moxios.stubRequest pushes requests to moxios.requests, so, you'll be able to analyze all requests after responding to the last call.

The code will look something like this (considering you have 3 requests to do):

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");
});
Igor Bykov
  • 2,532
  • 3
  • 11
  • 19