testinge2e-testingweb-api-testing

In httpYac how to assign the current system time to a variable and use this variable in http request payload?


For my e2e tests I'd like to get the current date and time and use this dateTime string in the payload body, like this:

### Precondition: Create a contract with current time stamp in ISO format

# currentDateTimeStringInISO = some JavaScript code 

POST http://localhost:8080/api/rest/v1/contracts/12345678
Authorization: Basic user user
Content-Type: application/json

{
  "valid_until": currentDateTimeStringInISO,
  ...
}

> {% 
  client.test("Status code is 201", function() {
    client.assert(response.status === 201, "Expected status code 201 for contract creation");
  });
  client.test("Contract status is VALID", function() {
    client.assert(response.body.contractStatus === "VALID", "Expected status to be VALID");
  });
%}

What's the correct httpYac syntax for this? I read the official doc but did not get this work.

Thanks, Nicole


Solution

  • I found the solution from another thread: Is there a compatible way to create a dynamic date in .http files?

    {{
      let now = new Date();
      // Add 1 second
      let cetTime = new Date(now.getTime() + 1000);
      // Adjust to CET winter time (CET, UTC+1)
      let cetDate = new Date(cetTime.getTime() + (1 * 60 * 60 * 1000));
      // Export as full ISO string with explicit CET offset
      exports.currentTime = berlinDate.toISOString().replace('Z', '+01:00');
    }}
    POST http://localhost:8080/api/rest/v1/contracts
    Authorization: Basic user user
    Content-Type: application/json
    
    {
      "expiryDate": "{{currentTime}}",
      ...
    }
    
    @response
    {{
      console.info('Generated currentTime was: ' + currentTime);
    }}
    
    ...assertions
    

    Inside the JSON payload, the double quote outside the {{}} is crucial.