API Reference
The scripting feature is available only in the paid version.
Global Variables
The following global variables available in the scripting.
Global Variable | Description |
---|---|
tc | The main object for all API access |
expect | Chai library for assertions |
assert | Chai library for assertions |
btoa | Base64 encoding |
atob | Base64 decoding |
Built in Libraries
The following built-in libraries are available in the scripting
Library Name | Description |
---|---|
ajv (opens in a new tab) | JSON schema validator |
ajv-formats (opens in a new tab) | Additional formats for JSON schema validation |
axios (opens in a new tab) | Promise-based HTTP client |
buffer (opens in a new tab) | Buffer class for working with binary data |
chai (opens in a new tab) | Assertion library |
crypto-js (opens in a new tab) | JavaScript library for cryptographic operations |
fast-xml-parser (opens in a new tab) | XML parser and validator |
fs (opens in a new tab) | File system module |
http (opens in a new tab) | HTTP module |
https (opens in a new tab) | HTTPS module |
papaparse (opens in a new tab) | CSV parser and processor |
stream (opens in a new tab) | Readable and writable streams |
tough-cookie (opens in a new tab) | HTTP cookie handling library |
url (opens in a new tab) | URL parsing and formatting |
util (opens in a new tab) | Utility functions |
uuid (opens in a new tab) | UUID generator |
How to use built-in libraries
// e.g: to use axios library
const axios = require('axios');
Request
Get the request object. Only headers and body can be modified.
Property | Description |
---|---|
tc.request.id | The ID of the request. |
tc.request.name | The name of the request. |
tc.request.url | The URL of the request. |
tc.request.method | The HTTP method of the request. |
tc.request.headers | An array of key-value pairs representing the headers of the request. |
tc.request.body | The body of the request. |
tc.request.auth | The authentication object of the request. |
tc.request.getHeader() | A function to get the value of a specific header. |
tc.request.setHeader() | A function to set the value of a specific header. |
tc.request.setBody() | A function to set the body of the request. |
Headers
tc.request.headers
is an array of key-value pairs representing the headers of the request.- Each header object has the following properties:
name
: The name of the header.value
: The value of the header.isDisabled
: A boolean value indicating whether the header is disabled.
Body
tc.request.body
is an object representing the body of the request.
body type
type RequestBody = {
type: BodyType,
raw: string | undefined,
form: KeyValue[] | undefined,
files: KeyValue[] | undefined,
graphql: GraphqlBody | undefined,
binary: string | undefined
}
For more details, refer to the Typescript Definition file.
setHeader
tc.request.setHeader(name: string, value: string): void
- Set the value of a specific header.
getHeader
tc.request.getHeader(name: string): string | undefined
- Get the value of a specific header.
setBody
tc.request.setBody(body: string | object | GraphqlBody | undefined, type?: BodyType): void
- Set the body of the request.
Sample Usage
// set JSON body
tc.request.setBody({
color:"red"
})
// set XML body
tc.request.setBody("<xml> xml_content </xml>");
// set Text body
tc.request.setBody("plain text body here");
// set Multi-part form
tc.request.setBody({
form: [{
name: "test",
value: "123"
}],
files: [{
name: "file1",
value:"file_path_relative_or_absolute"
}]
}, "formdata")
// set form-urlencoded
tc.request.setBody({
form: [{
name: "test",
value: "123"
}]
}, "formencoded")
// set GraphQL body
tc.request.setBody({
query: `query {
countries {
name
}
}`,
variables: {
"data": {
"hero": {
"name": "R2-D2"
}
}
}
}, "graphql")
// set Binary File body
tc.request.setBody("file_path/test.csv", "binary")
Response
Get the response object of the request. This object is read-only.
Property | Description |
---|---|
tc.response.status | The status code of the response. |
tc.response.time | The time taken for the request in milliseconds. |
tc.response.size | The size of the response in bytes. |
tc.response.contentType | The content type of the response. |
tc.response.json | The response body parsed as JSON. |
tc.response.text | The response body as plain text. |
tc.response.passed | Indicates whether the tests passed or failed in the Tests tab. |
tc.response.headers | An array of key-value pairs representing the headers of the response. |
tc.response.cookies | An array of key-value pairs representing the cookies of the response. |
tc.response.getHeader() | A function to get the value of a specific header. |
tc.response.getBinary() | A function to get the binary response as Buffer. |
Headers
tc.response.headers
is an array of key-value pairs representing the headers of the request.- Each header object has the following properties:
name
: The name of the header.value
: The value of the header.
Cookies
tc.response.cookies
is an array of key-value pairs representing the cookies of the response.- Each cookie object has the following properties:
name
: The name of the header.value
: The value of the header.
getHeader
tc.response.getHeader(name: string): string | undefined
- Get the value of a specific header.
getBinary
tc.response.geBinary(): Buffer | undefined
- Gets the binary response as a Buffer.
Info
- Get the additional information of the current executing request
Property | Description |
---|---|
tc.info.environmentName | The environment used for current request. |
tc.info.requestName | The current request name. |
tc.info.collectionName | The collection name of the request. |
tc.info.folderName | The folder name of the request. |
tc.info.currentIteration | The current iteration number. |
tc.info.totalIterations | The total number of iterations. |
Methods
getVar
tc.getVar(variableName: string): string
- Get the value of an environment variable.
Sample Usage
var name = tc.getVar("locationName");
var numberString = tc.getVar("incrementNumber");
var number = parseInt(numberString);
setVar
tc.setVar(variableName: string, value: any, scope?: "local" | "global" | "request"): void
- Set the value of an environment variable.
Sample Usage
// To save to active environment
tc.setVar(varName, value);
// To save to local environment
tc.setVar(varName, value, "local");
// To save to global environment
tc.setVar(varName, value, "global");
// To set collection or request level variables
tc.setVar(varName, value, "request");
setParam
tc.setParam(paramName: string, value: any): void
- Add or update a query parameter in the URL.
loadModule
tc.loadModule(moduleName: string, version?: string): Promise<any>
- Load and get a node module from the npm registry.
Sample Usage
console.log("load node module");
var moment = await tc.loadModule("moment");
// use moment specific version
var moment = await tc.loadModule("moment", "2.30.0");
console.log(moment().format());
tc.setVar("date", moment().format());
Documentation: Node Libraries
loadFromPath
tc.loadFromPath(modulePath: string): any
- Load a module from the specified folder path.
- The module path can be relative to the project root or an absolute path.
Sample Usage
console.log("load local module");
var moment = tc.loadFromPath("thunder-tests/packages/node_modules/moment");
Documentation: Node Libraries
readFile
tc.readFile(path: string, encoding?: string): Promise<string | undefined>
- Read a file from disk.
path
: The path to the file, relative to the project root or an absolute path.encoding
(optional): The encoding to use. Can be "utf8" or "base64". If not specified, "utf8" will be used.
Sample Usage
// To read a text file
await tc.readFile("filePath");
// To read file in base64 encoding
await tc.readFile("filePath", "base64");
exec
tc.exec(command: string): Promise<any>
- Execute a command and return the result.
Sample Usage
await tc.exec("node --version");
getCookies
tc.getCookies(url?: string): Promise<Cookie[]>
- Get all cookies in the cookie store.
Sample Usage
// get all cookies in store
var list = await tc.getCookies();
// get all cookies for current url
var listDomain = await tc.getCookies("url");
var listDomain = await tc.getCookies(tc.request.url);
clearCookies
tc.clearCookies(url?: string, name?: string): Promise<void>
- Clear existing cookies.
Sample Usage
// clear all cookies in store
await tc.clearCookies();
// clear all cookies for current domain
await tc.clearCookies("url");
await tc.clearCookies(tc.request.url);
// clear single cookie by name of cookie
await tc.clearCookies(tc.request.url, "cookieName");
setCookie
tc.setCookie(url: string, name: string, value: string): Promise<void>
- Set a cookie in the cookie store.
Sample Usage
// set cookie for current url
await tc.setCookie("https://www.thunderclient.com", "cookieName", "cookieValue");
await tc.setCookie(tc.request.url, "cookieName", "cookieValue");
delay
tc.delay(ms: number): Promise<void>
- Delay the execution for the specified number of milliseconds.
Sample Usage
// delay for 1 second.
await tc.delay(1000);
test
tc.test(name: string, result: boolean | (() => boolean | void)): void
- Perform a test assertion.
Sample Usage
tc.test("Custom test name", true);
// assert response code is 200 without assertion library
tc.test("Response code is 200", tc.response.status === 200);
// assert response code is 200 with chai library
tc.test("Response code expect to be 200", function () {
expect(tc.response.status).to.equal(200);
})
Documentation: Assertions
runRequest
tc.runRequest(reqId: string): Promise<ResponseModel>
- Run a request from the script.
Sample Usage
var result = await tc.runRequest("reqId");
// to get the request id dynamically
var result = await tc.runRequest(tc.request.id);
console.log(result);
Documentation: Send Requests
retryRequest
tc.retryRequest(): Promise<ResponseModel>
- Retry a request from the script. This will not execute the pre-reqs and pre-script.
Sample Usage
await tc.retryRequest();
Documentation: Retry Request
skipRequest
tc.skipRequest(reqId: string): void
- Skip a request from execution in collection run.
Sample Usage
tc.skipRequest("reqId");
chartHTML
tc.chartHTML(template: string, data: any): void
- Set the chart template and data. See Chart View for more details.
Typescript Definition
- Please refer to the
tc-types.d.ts
file for the typescript definition of thetc
object.
tc-types.d.ts file
tc-types.d.ts
// version 2.21.4
declare var tc: tcType;
declare var expect: any;
declare var atob: any;
declare var btoa: any;
interface tcType {
/**
* Get Environment variable value
* @param variableName variable name
*/
getVar(variableName: string): string;
/**
* Set Environment variable value
* @param variableName variable name
* @param value variable value
* @param scope [optional] environment scope with values: local, global and request
*/
setVar(variableName: string, value: any, scope?: "local" | "global" | "request"): void;
/**
* Add or update the query parameter of the URL
* @param paramName query parameter name
* @param value parameter value
* @since 2.11.0
*/
setParam(paramName: string, value: any): void;
/**
* Load and get node module from npm registry
* @param moduleName module name
* @param version [optional] module version, if empty latest version will be used
*/
loadModule(moduleName: string, version?: string): Promise<any>;
/**
* Load a module from the specified folder path
* @param modulePath module path relative to project root or absolute path
* @since 2.21.0
*/
loadFromPath(modulPath: string): any;
/**
* Read the file from disk
* @param path file path relative to project root or absolute path
* @param encoding [optional] encoding to use base64 or utf8. if empty utf8 will be used
*/
readFile(path: string, encoding?: string): Promise<string | undefined>;
/**
* Executes the command and returns the result
* @param command command to execute
*/
exec(command: string): Promise<any>;
/**
* Get all cookies in cookie store
* @param url [optional] to get cookies for url, if empty all cookies will be returned
* @since 2.14.0
*/
getCookies(url?: string): Promise<Cookie[]>;
/**
* Clear all existing cookies
* @param url [optional] to clear cookies for url, if empty all cookies will be cleared
* @param name [optional] to clear cookie by name, if empty all cookies for the url are cleared
*/
clearCookies(url?: string, name?: string): Promise<void>;
/**
* Set cookie in cookie store
* @param url the url to set cookie for
* @param name cookie name
* @param value cookie value
* @since 2.14.0
*/
setCookie(url: string, name: string, value: string): Promise<void>;
/**
* Delay the execution for the specified milliseconds
* @param ms the delay time in milliseconds
* @since 2.9.2
*/
delay(ms: number): Promise<void>;
/**
* Test assertion (Only works in Post Request Script)
* @param name the name of the test
* @param result the result of the test -> boolean or function that returns false
* or throws exception
* @since 2.10.0
*/
test(name: string, result: boolean | (() => boolean | void)): void;
/**
* Run Request from the script
* @param reqId the request id
* @since 2.9.0
*/
runRequest(reqId: string): Promise<ResponseModel>;
/**
* Retry Request from the script. This will not execute the pre-reqs and pre script
* @since 2.17.5
*/
retryRequest(): Promise<ResponseModel>;
/**
* Skip Request from execution in collection run
* @param reqId the request id
* @since 2.16.0
*/
skipRequest(reqId: string): void;
/**
* Set the chart template and data
* @param template chart template HTML string
* @param data chart data
* @since 2.17.0
*/
chartHTML(template: string, data: any): void;
/**
* Get the Request Info
* @since 2.15.0
*/
info: InfoModel;
/**
* Get the Request object (Only Headers can be modified)
*/
request: RequestModel;
/**
* Get the Response object (read-only)
*/
response: ResponseModel;
}
type RequestModel = {
id: string;
name: string;
url: string;
method: string;
headers: KeyValue[];
body: RequestBody | undefined;
auth: Authentication | undefined;
getHeader(name: string): string | undefined;
setHeader(name: string, value: string): void;
/**
* Set Request body
*/
setBody(body: string | object | GraphqlBody | undefined, type?: BodyType): void;
}
type ResponseModel = {
status: number;
time: number;
size: number;
contentType: string;
headers: KeyValue[];
cookies: KeyValue[];
json: any;
text: string;
getHeader(name: string): string | undefined;
getBinary(): Buffer | undefined;
}
type RequestBody = {
type: BodyType,
raw: string | undefined,
form: KeyValue[] | undefined,
files: KeyValue[] | undefined,
graphql: GraphqlBody | undefined,
binary: string | undefined
}
type KeyValue = {
name: string,
value: string,
isDisabled?: boolean | undefined
}
type BodyType = "none"|"text"|"json"|"xml"|"formdata"|"formencoded"|"graphql"|"binary";
type GraphqlBody = {
query: string,
variables?: string | undefined
}
type Cookie = {
key: string;
value: string;
expires?: string; // date in ISO 8601 format
domain: string;
path: string;
hostOnly: boolean;
httpOnly?: boolean;
creation: string; // date in ISO 8601 format
lastAccessed: string; // date in ISO 8601 format
}
type InfoModel = {
environmentName: string,
requestName: string,
collectionName: string,
folderName: string,
currentIteration: number,
totalIterations: number
}
Autocomplete
- If you are using external JS files, you can refer to the
tc-types.d.ts
file for autocomplete suggestions. - Copy
tc-types.d.ts
to your project and reference it at the top for VS Code autocomplete suggestions.
// @ts-check
/// copy tc-types.d.ts file for vscode autocompletion on tc object
/// <reference path="./tc-types.d.ts" />
TS Validation
- Use
// @ts-check
at the top of the script to enable TypeScript validation.