When we use the IntelliJ HTTP Client we can write Javascript for the pre-request and response handlers. The Javascript code must be in between {% …​ %} delimeters. If we want to re-use Javascript functions in the pre-request or response handlers we can store them in an external Javascript file. Then we use the import statement to import either the whole file or specify explicitly the code we want to import. This way we can reuse code for different pre-request and response handlers.

In the following example we import the createUsername function from the external scripts/username.js file and use it in the pre-request handler. In the response handler we import the external file scripts/validate-200-response.js and the code from the file is executed when the response is available.

// File: scripts/username.js
function createUsername() {
    const usernames = ["mrhaki", "hubert"];
    const randomIndex = (Math.floor(Math.random() * 11) % 2);

    // Return mrhaki or hubert as username.
    return usernames[randomIndex];
}

export {createUsername};
// File: scripts/validate-200-response.js
client.test("Response is OK", function () {
    client.assert(response.status === 200);
});
### POST JSON payload to /anything
< {%
    // Refer to createUsername function from external Javascript file.
    import {createUsername} from './scripts/username';

    // Use function createUsername.
    request.variables.set("username", createUsername());
%}

POST https://ijhttp-examples.jetbrains.com/anything

{
  "username": "{{username}}"
}

> {%
    // Validate 200 response from external file. 
    import './scripts/validate-200-response';

    client.test("Response has username set", function () {
        client.log("Username -> " + response.body.json.username);
        client.assert(["mrhaki", "hubert"].includes(response.body.json.username));
    });
 %}

Written with IntelliJ 2023.2.4.

shadow-left