0

I am able to get the API Response Time (duration) in the 'makeAPICall' function. Now I need to pass it(the value of the duration variable)to another async function. I am wondering if you could please provide the solution?

const makeApiCall = ClientFunction(() => {
  console.time("timer1");
  const testLocation = () => fetch('https://xxxxxx',
    {method : 'GET',
      headers:{
        hash: 'xxxxx',
        id: 'xxxxxxxxc'
      }
    })
    .then(response => response.json())
    .then(data => {
      let duration = console.timeEnd("timer1");
      console.log(duration);
    });
  return testLocation();
});



test('test', async t => {
  await makeApiCall();
  console.log(duration)?????
});
Negin
  • 2,332
  • 17
  • 22

2 Answers2

4

1st problem: console.timeEnd does not return anything, it print the ellapsed time to the console. Use performance.now() instead or just Date.

2)You should then return the duration from the last then.

const makeApiCall = ClientFunction(() => {
  const start = new Date().getTime();
  const testLocation = () => fetch('https://xxxxxx',
    {method : 'GET',
      headers:{
        hash: 'xxxxx',
        id: 'xxxxxxxxc'
      }
    })
    .then(response => response.json())
    .then(data => {
       const end = new Date().getTime();
       return end - start;
    });
  return testLocation();  // This returns a Promise<number>
});



test('test', async t => {
  const duration = await makeApiCall();
  console.log(duration)?????
});
hansmaad
  • 18,417
  • 9
  • 53
  • 94
  • @ hansmaad Thanks for your reply. I got the other error though. I have updated my first post above with the new error – Negin May 27 '21 at 06:20
  • @Negin `console.timeEnd` does not return the time, it prints it to console. I changed my answer. – hansmaad May 27 '21 at 06:31
0

You can try the following approach with the t.request method that TestCafe provides for API testing.

fixture `Test API`;

test('Simple Test', async t => {
    const startTime = Date.now();

    const response = await t.request('https://jsonplaceholder.typicode.com/comments');
    const duration = Date.now() - startTime;

    console.log(`request duration is ${duration}ms`); //request duration is 336ms
    await t.expect(response.status).eql(200);
});

However, please note that a request's execution time will not be absolutely accurate because apart from execution of the request itself, the time required to process TestCafe's t.request command, the time for messaging and overhead costs will also be included in the measurement. You can use this measurement as a comparative estimate of the query execution time. Also, the timeout option is available.

Helen Dikareva
  • 1,026
  • 6
  • 7