pactumjs / pactum

REST API Testing Tool for all levels in a Test Pyramid
https://pactumjs.github.io
MIT License
538 stars 52 forks source link

Pactum spec makes multiple api calls #328

Closed hemant-bs closed 5 months ago

hemant-bs commented 6 months ago

Describe the bug I have started my API automation using cucumber-pactum using this template. When I run my scenario my API is being hit multiple times, when I added a debugger to check which all calls are sending request I discovered these 3 commands are hitting request individually.

await spec.withBearerToken(TOKEN); 
await spec.response().should.have.status(parseInt(code));
await spec.expectJsonLike(body);

To Reproduce

My cucumber feature file

    Given User makes a GET request to  <endpoint> API
    And I set basic authentication credentials
    When User receives a response
    Then User expects response should have a status <code>
    And User validates response for <test_data>

My steps.js

Before(() => {
  spec = pactum.spec();
  request.setDefaultTimeout(25000);
  setDefaultTimeout(25000);
});

Given(/^User makes a (.*) request to  (.*) API$/, { timeout: 600 * 1000 }, async function (method,endpoint) {

      await spec[method.toLowerCase()](endpoint);

});

Given(/^I set basic authentication credentials$/, async function () {
  await spec.withBearerToken(TOKEN); //first time call
});

When('User receives a response', async function () {
  const response = await spec.toss(); // second call
  globalResponse = response.body;
  console.log(globalResponse)
});

Then(/^User expects response should have a status ([0-9]+)$/, async function (code) {
  await spec.response().should.have.status(parseInt(code)); 
});

Then(/^User validates response for ([0-9a-zA-Z -_]+)$/, { timeout: 600 * 1000 }, async function (request) {

    await spec.expectJsonSchema(someBody); // third call
    spec = pactum.spec();
  }

Expected behavior

While chaining the requests it should call the API only once

Software (please complete the following information):

Additional context Add any other context about the problem here.

ASaiAnudeep commented 5 months ago

Hello @hemant-bs,

await statement should be only used when we wanted to make a request and get the response.

Read More