简体   繁体   中英

Testing multiple responses from POST request

I'm trying to update a Jest test for a function that previously created a single entry and now creates multiple entries. The actual code that making the real API requests works. The issue I'm having is that I am unable to format the mock response to be the same shape as the real response.

OLD REAL REQUEST/RESPONSE: made API call with request object, got a response object with a result attribute containing an id (used for a subsequent backend call)

UPDATED REAL REQUEST/RESPONSE: uses Promise.all to make multiple API calls with multiple request objects and get array of response objects, each response has a result attribute and corresponding result.id

OLD MOCK: starts with a 'request object' with a 'result' key and data value that mimics result data needed in the jest test This was parsed for the mock call by

create: () => {
  return new Promise((resolve, _reject) => {
    setTimeout(() => {
      resolve(requestObject);
    }, fakeRequestTimeoutDuration);
  });
}

UPDATED MOCK: starts with array of two 'request objects'. What I want is an array of two resolved promises, both containing the correct corresponding result attribute and result.id This is what I have currently, which doesn't work

create: async () => {
  return Promise.all(
    requestObjects.map(requestObject => {
      return new Promise((resolve, _reject) => {
        setTimeout(() => {
          resolve(requestObject);
            }, fakeRequestTimeoutDuration);
        });
      })
    );
  }
},

I'm totally lost. In my mock response, I keep getting nested arrays, and either unresolved promises or the data is mapped so that it repeats multiple times (what the above is doing now). For the test, I just need an array of the two resolved response objects. What am I doing wrong here? Based on console.log it looks like something is being invoked twice, but that doesn't make any sense. Help!!! (Please let me know if any additional detail would be helpful!)

Is it what you trying to achieve?

const requestObjects = [1, 2];
const fakeRequestTimeoutDuration = 500;

const testObj = {
    create: async () => Promise.all(
        requestObjects.map(requestObject => {
            return new Promise((resolve, _reject) => {
                setTimeout(() => {
                    resolve(requestObject);
                }, fakeRequestTimeoutDuration);
            });
        })
    )
};

const [obj1, obj2] = await testObj.create();
console.log(obj1) // 1
console.log(obj2) // 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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