Calling our endpoint

For the first call to our server, we have broken it down into three steps:

  1. When the client creates a POST request to /users
  2. And attaches a generic empty payload
  3. And sends the request

In the first step, we will create a new request object and save it as a file-scoped variable, making it available to be accessed by subsequent steps. In the second, we will attach an empty payload to the request; however, this is already the default behavior of superagent, so we can simply return from the function without doing anything. In the third step, we will send the request and save the response in another variable.

You should now update the start of your spec/cucumber/steps/index.js file to the following snippet:

import superagent from 'superagent';
import { When, Then } from 'cucumber';
let request;
let result;
let error;

When('the client creates a POST request to /users', function () {
request = superagent('POST', 'localhost:8080/users');
});

When('attaches a generic empty payload', function () {
return undefined;
});

When('sends the request', function (callback) {
request
.then((response) => {
result = response.res;
callback();
})
.catch((errResponse) => {
error = errResponse.response;
callback();
});
});

Our third step definition involves sending a request to the server and waiting for a response; this is an asynchronous operation. To ensure the next step won't run before this asynchronous operation is complete, we can pass a callback function into the code function as its last parameter. Cucumber will wait for the callback function to be called before moving on to the next step. Here, we are executing the callback only after the result has been returned and we have saved it to the result variable.

Now, when we run our E2E tests again, the first three steps should pass.

$ yarn run test:e2e
...P--

Warnings:
1) Scenario: Empty Payload
When the client creates a POST request to /users
And attaches a generic empty payload
And sends the request
? Then our API should respond with a 400 HTTP status code
- And the payload of the response should be a JSON object
- And contains a message property which says "Payload should not be empty"

1 scenario (1 pending)
6 steps (1 pending, 2 skipped, 3 passed)