### Example .env file format
Source: https://docs.thunderclient.com/features/environments
Variables in a .env file should be in a key=value format.
```dotenv
key=value
name=thunder
number=25543
```
--------------------------------
### Install Thunder Client CLI Globally
Source: https://docs.thunderclient.com/cli/install
Install the CLI globally using npm. This command should be run in your terminal.
```bash
npm i -g @thunderclient/cli
```
--------------------------------
### Open Run Collection UI with Auto-Run
Source: https://docs.thunderclient.com/cli/run-collection
Launch the ThunderClient Run Collection UI and automatically start the execution of the specified collection.
```bash
tc --col 'User' --ui
```
--------------------------------
### Clipboard Example with Button and Feedback
Source: https://docs.thunderclient.com/testing/chart-view
Creates a button that, when clicked, attempts to copy predefined text to the clipboard using `parent.postMessage()` and provides user feedback on success or failure.
```javascript
var html = `
`
pc.chartHTML(html);
```
--------------------------------
### Get npm Global Prefix
Source: https://docs.thunderclient.com/cli/jetbrains
Prints the global node_modules bin folder path, which can help in locating the 'tc' executable.
```bash
# prints the global node_modules bin folder
npm config get prefix
```
--------------------------------
### Plain Text Environment Variable
Source: https://docs.thunderclient.com/features/environments/encrypted-envs
Example of an environment variable stored in plain text format. This is used in Free, Starter, and Business plans.
```json
{
"name": "color",
"value": "red",
"secret": true
}
```
--------------------------------
### Environment Variables
Source: https://docs.thunderclient.com/scripting/api
Functions for getting, setting, and replacing environment variables within ThunderClient scripts.
```APIDOC
## Environment Variables
### `tc.getVar(variableName: string): string`
#### Description
Retrieves the value of an environment variable.
### `tc.setVar(variableName: string, value: any, scope?: "local" | "global" | "request"): void`
#### Description
Sets the value of an environment variable. The scope can be specified as 'local', 'global', or 'request'.
### `tc.replaceVars(variableName: string): string`
#### Description
Replaces environment variables within a given string.
```
--------------------------------
### Pre-Request Script for Setting Environment Variables
Source: https://docs.thunderclient.com/scripting/custom-filters
Illustrates a pre-request script that generates a UUID and sets it as an environment variable. This example shows how to use `tc.setVar` to save values to the active, local, or global environment.
```javascript
function preFilter1() {
console.log("set env variable example");
let uuid = uuid4();
// ---- save to active environment
tc.setVar("uuidFromScript", uuid);
// ---- save to local environment
// tc.setVar("uuidFromScript", uuid, "local");
// ---- save to global environment
// tc.setVar("uuidFromScript", uuid, "global");
}
module.exports = [preFilter1];
```
--------------------------------
### Generate Random GUID
Source: https://docs.thunderclient.com/features/system-variables
Use `{{#guid}}` to generate a random UUID. This is useful for unique identifiers.
```text
{{#guid}}
```
--------------------------------
### Dark Mode Styles Override
Source: https://docs.thunderclient.com/testing/chart-view
Example of how to override default table styles for dark mode using the `.vscode-dark` class.
```css
/* for dark mode use .vscode-dark to override */
.vscode-dark th, .vscode-dark td {
border-bottom: 1px solid #555;
}
```
--------------------------------
### URL Query Parameters: Postman vs. Thunder Client
Source: https://docs.thunderclient.com/scripting/postman
Demonstrates how to get and set URL query parameters in both Postman and Thunder Client scripts. This is useful for dynamically modifying request URLs.
```javascript
// Postman script
// Get a query param value
const userId = pm.request.url.getQueryParam("userId");
// Add or update a query param
pm.request.url.addQueryParams({
debug: "true",
});
```
```javascript
// Thunder Client script
// Get a query param value
const userId = tc.request.url.getParam("userId");
// Add or update a query param
tc.request.url.setParam("debug", "true");
```
--------------------------------
### Run Thunder Client Collection in GitHub Actions
Source: https://docs.thunderclient.com/cli/ci-cd
This snippet shows how to install the Thunder Client CLI and run a collection within a GitHub Actions workflow. It generates reports in CLI, JSON, XML, and HTML formats and logs detailed output.
```yaml
# This is a basic workflow to help you get started with Actions
name: TestBuild
# Controls when the workflow will run
on:
# Triggers the workflow on push or pull request events but only for the "master" branch
# push:
# branches: [ "main" ]
# pull_request:
# branches: [ "main" ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v4
# Install Node on the runner
- name: Install Node
uses: actions/setup-node@v4
with:
node-version: 20
# Install Thunder Client CLI
- name: Install Thunder Client CLI
run: |
npm install -g @thunderclient/cli
- name: Make Directory for results
run: mkdir -p thunder-reports
# Run the Thunder Client collection
- name: Run Thunder Client collection
run: |
tc --col "ColNameOrId" --report cli,json,xml,html --log 8
# Upload the contents of the test results directory to workspace
- name: Output the run Details
if: ${{ always() }}
uses: actions/upload-artifact@v4
with:
name: RunReports
path: thunder-reports
```
--------------------------------
### Get Environment Variables
Source: https://docs.thunderclient.com/scripting/variables
Retrieve the value of an environment variable by its name. Use this to access configuration or secrets stored in your environment.
```javascript
let apiKey = tc.getVar("API_KEY");
let token = tc.getVar("token");
```
--------------------------------
### Save Variable to Active Environment
Source: https://docs.thunderclient.com/features/system-variables
Example of saving a generated variable (e.g., first name using faker-js) to the active environment.
```javascript
// to save Env value to Active Environment
tc.setVar("firstName", faker.person.firstName());
```
--------------------------------
### Get Environment Variable
Source: https://docs.thunderclient.com/scripting/api
Retrieve the value of an environment variable. Useful for dynamic request parameters or storing configuration.
```javascript
var name = tc.getVar("locationName");
var numberString = tc.getVar("incrementNumber");
var number = parseInt(numberString);
```
--------------------------------
### Send Custom GET Request with Axios
Source: https://docs.thunderclient.com/scripting/send-request
Send custom HTTP requests using the Axios library. This is useful for executing requests not defined within Thunder Client directly from scripts.
```javascript
const axios = require('axios');
const response = await axios.get("https://www.thunderclient.com/welcome");
console.log(response);
```
--------------------------------
### Environment Variables
Source: https://docs.thunderclient.com/scripting/api
Manage environment variables by getting their values using `tc.getVar()` and setting them using `tc.setVar()`. Variables can have local, global, or request scopes.
```APIDOC
## Environment Variables
### Description
Manage environment variables by getting their values using `tc.getVar()` and setting them using `tc.setVar()`. Variables can have local, global, or request scopes.
### Methods
* `tc.getVar(variableName: string): string`
* Get the value of an environment variable.
* `tc.setVar(variableName: string, value: any, scope?: "local" | "global" | "request"): void`
* Set the value of an environment variable.
**Sample Usage**
```javascript
// 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");
```
```
--------------------------------
### Define Custom Filters (Deprecated)
Source: https://docs.thunderclient.com/scripting/custom-filters
Example of creating a JavaScript file to define custom filter functions. This file can include functions for various tasks, such as file reading, command execution, and cryptographic operations. These functions can be imported and used in Thunder Client scripts.
```javascript
const CryptoJS = require("crypto-js");
const { v4: uuid4 } = require("uuid");
async function appendString(input, param1) {
// read a file
var data = await tc.readFile(input);
// execute a command
var result = await tc.exec("echo testing");
return `${input} ${data} ${result}`;
}
function customHmac(input) {
console.log("running custom hmac");
var secretValue = tc.getVar("secret");
let encoded = CryptoJS.HmacSHA256(input, secretValue);
return encoded.toString(CryptoJS.enc.Base64);
}
module.exports = [customHmac, appendString];
```
--------------------------------
### Convert JSON Response to HTML Table
Source: https://docs.thunderclient.com/testing/chart-view
This generic example converts any JSON array response into an HTML table. Styles can be modified as needed, including dark mode overrides.
```javascript
var response = tc.response.json;
var html = `
`
pc.chartHTML(html, response);
```
--------------------------------
### Sample JSON Schema
Source: https://docs.thunderclient.com/testing/schema
An example of a JSON schema used for validating API responses. This schema defines the structure, data types, and required fields for a JSON object.
```json
{
"type": "object",
"additionalProperties": false,
"properties": {
"fraction": {
"type": "number"
},
"balance": {
"type": "number"
},
"bignumber": {
"type": "integer"
},
"isNumber": {
"type": "null"
}
},
"required": [
"balance",
"bignumber",
"fraction",
"isNumber"
],
"title": "Welcome4"
}
```
--------------------------------
### Retry Request with Exponential Delay
Source: https://docs.thunderclient.com/scripting/send-request
The `tc.retryRequest()` function retries the current request. It does not execute pre-reqs or pre-scripts. Use `tc.runRunRequest()` to include them. This example implements an exponential backoff strategy.
```javascript
let incrementCount = parseInt(tc.getVar('incrementCount') || "0");
let code = tc.response.status;
if(incrementCount <= 3 && code !== 200)
{
incrementCount = incrementCount + 1
tc.setVar('incrementCount', incrementCount)
console.log("retrying request", incrementCount);
await tc.delay(incrementCount * 1000); // exponential delay of 1 secs
await tc.retryRequest(); // <--- retry request
}
else
{
tc.setVar('incrementCount', 0);
console.log("reset incrementCount = 0");
}
```
--------------------------------
### Importing a Built-in Library (Axios)
Source: https://docs.thunderclient.com/scripting/api
Demonstrates how to import and use the 'axios' library within a script. Ensure the library is available in your environment.
```javascript
const axios = require('axios');
```
--------------------------------
### URL Model Type
Source: https://docs.thunderclient.com/scripting/api
Represents a URL with methods to get and set query parameters.
```typescript
type UrlModel = string & {
getParam(name: string): string | undefined;
setParam(name: string, value: string): void;
}
```
--------------------------------
### Request Header Manipulation
Source: https://docs.thunderclient.com/scripting/api
Functions to get and set specific request headers by name.
```APIDOC
## Request Header Manipulation
### Description
Functions to get and set specific request headers by name.
### Methods
#### `tc.request.setHeader(name: string, value: string): void`
Set the value of a specific header.
#### `tc.request.getHeader(name: string): string | undefined`
Get the value of a specific header.
```
--------------------------------
### Attaching Environments to Collections
Source: https://docs.thunderclient.com/features/environments
This illustrates how environments can be attached to specific collections, establishing a precedence order.
```text
CollectionA -> EnvA
CollectionB -> EnvB
CollectionC -> EnvC
```
--------------------------------
### Open Request in UI and Auto-Run
Source: https://docs.thunderclient.com/cli/run-requests
Use the --ui argument to open a specific request in the ThunderClient extension UI and execute it automatically.
```bash
tc 'welcome' --ui
```
--------------------------------
### Get Unique Array Elements
Source: https://docs.thunderclient.com/scripting/filters
Filters an array to return only the unique elements, preserving the order of first appearance.
```Liquid
json.items | unique
```
--------------------------------
### Load and Use falso Module
Source: https://docs.thunderclient.com/features/system-variables
Illustrates loading the falso module and generating a user object to extract and set the first name as a variable.
```javascript
var falso = await tc.loadModule("@ngneat/falso");
var user = falso.randUser();
tc.setVar("firstName", user.firstName);
```
--------------------------------
### Load and Use chance Module
Source: https://docs.thunderclient.com/features/system-variables
Shows how to load the chance module and use it to generate a name, then set it as a variable.
```javascript
var Chance = await tc.loadModule("chance");
var chance = new Chance();
tc.setVar("firstName", chance.name());
```
--------------------------------
### Encrypted Environment Variable
Source: https://docs.thunderclient.com/features/environments/encrypted-envs
Example of an environment variable stored in an encrypted format. This is used in the Enterprise plan for enhanced security.
```json
{
"name": "color",
"value": "F4cuC3C1bmjrhpbG0uDj8A",
"secret": true,
"encrypted": true
}
```
--------------------------------
### AI Conversion Prompt
Source: https://docs.thunderclient.com/scripting/convert-ai
Use this prompt with AI tools to convert your existing API client scripts into Thunder Client format. Paste your script at the beginning of the prompt.
```text
[PASTE YOUR POSTMAN/OTHER API CLIENT SCRIPT HERE]
Convert the following script into Thunder Client format.
Use Thunder Client API Reference:
https://docs.thunderclient.com/scripting/api
https://docs.thunderclient.com/scripting/postman
```
--------------------------------
### Get Absolute Value
Source: https://docs.thunderclient.com/scripting/filters
The 'abs' filter returns the absolute value of a number. This is useful for ensuring a number is always positive.
```javascript
{{number | abs}}
```
--------------------------------
### Run All Collections
Source: https://docs.thunderclient.com/cli/run-collection
Execute all available collections. Supports skipping specific collections.
```bash
tc --col all
```
```bash
tc --col all --skip "ColA,ColB"
```
--------------------------------
### Load and Use faker-js Module
Source: https://docs.thunderclient.com/features/system-variables
Demonstrates loading the faker-js module in the Pre-Request Script to generate a first name and set it as a variable.
```javascript
var { faker } = await tc.loadModule("@faker-js/faker");
tc.setVar("firstName", faker.person.firstName());
```
--------------------------------
### Extract Substring
Source: https://docs.thunderclient.com/scripting/filters
Returns a portion of a string, specified by start and end indices. Negative indices count from the end of the string.
```Liquid
{{variable | substring(start, end)}}
```
```Liquid
{{variable | substring(-5)}}
```
--------------------------------
### Get Absolute File Path
Source: https://docs.thunderclient.com/scripting/api
Convert a relative file path to an absolute path. Useful for file operations with fs module.
```javascript
// To get Absolute path of the file from relative path
var fullPath = tc.getAbsolutePath("testing.json");
var dataString = "124";
// To save to a file using full path
fs.appendFileSync(fullPath, dataString)
```
--------------------------------
### Import JS File using require
Source: https://docs.thunderclient.com/scripting/import-files
Import a JavaScript file using the `require` function. Ensure the file path is correct and includes the `.js` extension. Relative paths are recommended when using Git Sync.
```javascript
const { helloWorld } = require("thunder-tests/test-import.js");
var result = helloWorld();
console.log(result);
```
--------------------------------
### Run Multiple Folders by Name or ID
Source: https://docs.thunderclient.com/cli/run-collection
Execute requests from multiple folders by providing a comma-separated list of their names or IDs.
```bash
tc --fol 'folNameOrId1,folNameOrId2'
```
--------------------------------
### Slice Array Elements
Source: https://docs.thunderclient.com/scripting/filters
Extracts a portion of an array based on start and end indices. Requires the input to be split into an array first.
```Liquid
{{variable | split(" ") | slice(1, 2)}}
```
--------------------------------
### Load Module from Path
Source: https://docs.thunderclient.com/scripting/api
Load a local module from a specified folder path using `tc.loadFromPath()`. The path can be relative to the project root or an absolute path.
```APIDOC
## Load Module from Path
### Description
Load a module from the specified folder path. The module path can be relative to the project root or an absolute path.
### Methods
* `tc.loadFromPath(modulePath: string): any`
* Load a module from the specified folder path.
**Sample Usage**
```javascript
console.log("load local module");
var moment = tc.loadFromPath("thunder-tests/packages/node_modules/moment");
```
```
--------------------------------
### Execute CLI Command
Source: https://docs.thunderclient.com/scripting/functions
Use the `exec` helper function to run a CLI command and retrieve its output. This is useful for integrating external tools or scripts.
```javascript
var result = await tc.exec("command");
```
```javascript
// example
var result = await tc.exec("node -v");
```
--------------------------------
### tc.retryRequest
Source: https://docs.thunderclient.com/scripting/api
Retries the current request without executing pre-request scripts or pre-request setup. This is useful for handling transient network issues.
```APIDOC
## tc.retryRequest
### Description
Retries a request from the script. This will not execute the **pre-reqs** or **pre-script**.
### Method
`tc.retryRequest(): Promise`
### Request Example
```javascript
await tc.retryRequest();
```
### Response
#### Success Response (200)
- **ResponseModel** - The response object from the retried request.
```
--------------------------------
### Get First Element of Array
Source: https://docs.thunderclient.com/scripting/filters
The 'first' filter returns the first element of an array. This is a convenient way to access the initial item in a list.
```javascript
json.items | first
```
--------------------------------
### Run Collection with Specific Environment
Source: https://docs.thunderclient.com/cli/run-collection
Execute a collection using a specified environment, overriding the default active environment.
```bash
tc --col 'colNameOrId' --env 'Staging'
```
--------------------------------
### Get Cookies
Source: https://docs.thunderclient.com/scripting/api
Retrieve cookies from the cookie store, optionally filtered by a URL, using `tc.getCookies()`. Returns a Promise resolving to an array of `Cookie` objects.
```APIDOC
## Get Cookies
### Description
Get all cookies in the cookie store, optionally filtered by a URL. Returns a Promise resolving to an array of `Cookie` objects.
### Methods
* `tc.getCookies(url?: string): Promise`
* `url` (optional): If provided, returns cookies only for the specified URL.
**Sample Usage**
```javascript
// 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);
```
```
--------------------------------
### Assertions using Chai Library (assert)
Source: https://docs.thunderclient.com/scripting/assertions
Employ the Chai library's 'assert' syntax for straightforward equality checks on response properties.
```javascript
tc.test("Response code is 200", function () {
assert.equal(tc.response.status, 200)
})
```
--------------------------------
### Get Absolute Path
Source: https://docs.thunderclient.com/scripting/api
Obtain the absolute path of a file using its relative path with `tc.getAbsolutePath()`. This is useful for file operations where an absolute path is required.
```APIDOC
## Get Absolute Path
### Description
Get the absolute path of the file. This is useful for file operations where an absolute path is required.
### Methods
* `tc.getAbsolutePath(relativePath: string): string`
* `relativePath`: The relative path to the file. (Right-click on the file in VS Code and select **Copy Relative Path**)
**Sample Usage**
```javascript
// To get Absolute path of the file from relative path
var fullPath = tc.getAbsolutePath("testing.json");
var dataString = "124";
// To save to a file using full path
fs.appendFileSync(fullPath, dataString)
```
```
--------------------------------
### Open Run Collection UI without Auto-Run
Source: https://docs.thunderclient.com/cli/run-collection
Launch the ThunderClient Run Collection UI without automatically running the collection, allowing for manual initiation.
```bash
tc --col 'User' --ui2
```
--------------------------------
### Request Body Manipulation
Source: https://docs.thunderclient.com/scripting/api
Methods to get and set the request body. Supports various content types including JSON, XML, form data, and GraphQL.
```APIDOC
## Request Body
### Description
Methods to get and set the request body. Supports various content types including JSON, XML, form data, and GraphQL.
### Properties
- `tc.request.body` (Object): The body of the request.
### Type Definition
```typescript
type RequestBody = {
type: BodyType,
raw: string | undefined,
form: KeyValue[] | undefined,
files: KeyValue[] | undefined,
graphql: GraphqlBody | undefined,
binary: string | undefined
}
```
### Methods
#### `tc.request.setBody(body: string | object | GraphqlBody | undefined, type?: BodyType): void`
Set the body of the request. Supports various types like JSON, XML, form data, files, GraphQL, and binary.
**Sample Usage**
```javascript
// set JSON body
tc.request.setBody({
color: "red"
})
// set XML body
tc.request.setBody(" xml_content ");
// 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")
```
```
--------------------------------
### Run Multiple Collections by Name or ID
Source: https://docs.thunderclient.com/cli/run-collection
Execute requests from multiple collections by providing a comma-separated list of their names or IDs.
```bash
tc --col "colNameOrId1,colNameOrId2"
```
--------------------------------
### Find Global 'tc' Path on Windows
Source: https://docs.thunderclient.com/cli/jetbrains
Use the 'where' command to find the global path to the 'tc' executable on Windows systems.
```bash
where tc
```
--------------------------------
### SSL Certificate Configuration
Source: https://docs.thunderclient.com/features/auth
Configure SSL certificates for authentication by providing paths to certificate files and optionally a passphrase. This setting applies per host.
```json
"thunder-client.certificates": [
{
"host": "thunderclient.io",
"certPath": "ssl/cert.pem",
"keyPath": "ssl/keyfile.key",
"pfxPath": "ssl/pfx.p12",
"passphrase": "test"
},
{
"host": "localhost:8081",
"pfxPath": "/Users/test/Documents/ssl/pfx.p12",
"passphrase": "test"
},
{
"host": "testing.com",
"certPath": "ssl/cert.pem",
"keyPath": "ssl/keyfile.key"
},
]
```
--------------------------------
### Generate Fake Data with Falso
Source: https://docs.thunderclient.com/scripting/libraries
Load and use the @ngneat/falso library to generate random user data. The generated data can be saved to the active environment.
```javascript
// example code to load falso module
var falso = await tc.loadModule("@ngneat/falso");
var user = falso.randUser();
tc.setVar("firstName", user.firstName);
```
--------------------------------
### Run Collection with Custom Delay Between Requests
Source: https://docs.thunderclient.com/cli/run-collection
Execute requests within a collection with a specified delay in milliseconds between each request.
```bash
tc --col 'colNameOrId' --delay 100
```
--------------------------------
### Generate ISO Date String
Source: https://docs.thunderclient.com/features/system-variables
Use `{{#dateISO}}` to generate a date in ISO format. Date manipulation using object notation is supported.
```text
{{#dateISO}}
{{#dateISO, {year: 1}}}
{{#dateISO, { year : -1, day: 3 } }}
```
--------------------------------
### Execute System Command
Source: https://docs.thunderclient.com/scripting/api
Execute a system command and retrieve its output. Useful for running external tools or scripts.
```javascript
await tc.exec("node --version");
```
--------------------------------
### Open Request in UI Without Auto-Run
Source: https://docs.thunderclient.com/cli/run-requests
Use the --ui2 argument to open a specific request in the ThunderClient extension UI without automatically running it.
```bash
tc 'welcome' --ui2
```
--------------------------------
### Get Cookies in ThunderClient Scripting
Source: https://docs.thunderclient.com/features/cookies
Retrieve cookie data using `tc.getCookies`. This method can fetch all cookies stored in the client or cookies associated with a specific URL. The returned value is a list of cookies.
```javascript
// 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);
```
--------------------------------
### Module Loading
Source: https://docs.thunderclient.com/scripting/api
Functions for loading Node.js modules from npm or a local path.
```APIDOC
## Module Loading
### `tc.loadModule(moduleName: string, version?: string): Promise`
#### Description
Loads a Node.js module from the npm registry. If a version is not specified, the latest version will be used.
### `tc.loadFromPath(modulPath: string): any`
#### Description
Loads a module from a specified folder path, which can be relative to the project root or an absolute path. Available since version 2.21.0.
```
--------------------------------
### Filter Array Elements
Source: https://docs.thunderclient.com/scripting/filters
The 'filter' filter allows you to filter elements in an array based on specified conditions. Supported operations include greater than, less than, equals, not equals, contains, starts with, and ends with.
```javascript
json.items | filter(id>5)
```
--------------------------------
### Run Selected Requests by Name or ID
Source: https://docs.thunderclient.com/cli/run-collection
Execute a specific list of requests identified by their names or IDs.
```bash
tc --reqlist "nameOrId1,nameOrId2,nameOrId3"
```
--------------------------------
### Execute a Request by Name or ID
Source: https://docs.thunderclient.com/cli/run-requests
Run a ThunderClient request using its name, ID, or a partial name. The output includes status, response with syntax highlighting, and test results.
```bash
tc 'requestNameOrId'
```
--------------------------------
### Execute Command
Source: https://docs.thunderclient.com/scripting/api
Execute shell commands and retrieve their output asynchronously using `tc.exec()`. This allows for system-level interactions within your scripts.
```APIDOC
## Execute Command
### Description
Execute a command and return the result. This allows for system-level interactions within your scripts.
### Methods
* `tc.exec(command: string): Promise`
* Execute a command and return the result.
**Sample Usage**
```javascript
await tc.exec("node --version");
```
```
--------------------------------
### Run Folder by Name or ID
Source: https://docs.thunderclient.com/cli/run-collection
Execute requests within a specified folder using its name or ID.
```bash
tc --fol 'folNameOrId'
```
--------------------------------
### Import Node Module from npm
Source: https://docs.thunderclient.com/scripting/libraries
Load an external Node module from the npm registry. You can specify a version for precise control. This feature is available in the paid version.
```javascript
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());
```
--------------------------------
### Generate Reports for Collection Run
Source: https://docs.thunderclient.com/cli/run-collection
Execute a collection and generate reports in specified formats (e.g., xml, html). Reports are saved in the 'thunder-reports' folder.
```bash
tc --col 'User' --report xml,html
```
--------------------------------
### Find Global 'tc' Path on macOS/Linux
Source: https://docs.thunderclient.com/cli/jetbrains
Use the 'which' command to find the global path to the 'tc' executable on macOS and Linux systems.
```bash
which tc
```
--------------------------------
### Run ThunderClient Debug Command
Source: https://docs.thunderclient.com/cli/help
Execute the debug command to view directory paths and Git Sync settings for troubleshooting CLI issues.
```bash
tc --debug
```
--------------------------------
### Setting Binary File Request Body
Source: https://docs.thunderclient.com/scripting/api
Sets the request body to a binary file. Provide the file path and specify 'binary' as the body type.
```javascript
tc.request.setBody("file_path/test.csv", "binary")
```
--------------------------------
### Assertions using Chai Library (expect)
Source: https://docs.thunderclient.com/scripting/assertions
Utilize the Chai library's 'expect' syntax for more expressive assertions on response properties like status codes.
```javascript
tc.test("Response code expect to be 200", function () {
expect(tc.response.status).to.equal(200);
})
```
--------------------------------
### Run Single Collection by Name or ID
Source: https://docs.thunderclient.com/cli/run-collection
Execute requests within a specified collection using its name or ID.
```bash
tc --col 'colNameOrId'
```
--------------------------------
### VS Code Proxy Setting
Source: https://docs.thunderclient.com/features/proxy
Configure the HTTP proxy server in VS Code's settings.json file. Replace username, password, host, and port with your actual proxy details.
```json
{
"http.proxy": "http://username:password@host:port"
}
```
--------------------------------
### Information Model Type
Source: https://docs.thunderclient.com/scripting/api
Provides details about the current execution environment, including request and collection names, and iteration counts.
```typescript
type InfoModel = {
environmentName: string,
requestName: string,
collectionName: string,
folderName: string,
currentIteration: number,
totalIterations: number
}
```
--------------------------------
### Import JS File using Environment Variable
Source: https://docs.thunderclient.com/scripting/import-files
Store the JavaScript file path in an environment variable using `tc.getVar()` to dynamically manage paths and avoid manual updates when files are moved.
```javascript
var scriptPath = tc.getVar("scriptPath");
var {helloWorld} = require(scriptPath);
var result = helloWorld();
console.log(result);
```
--------------------------------
### Run Collection with a Different Data File
Source: https://docs.thunderclient.com/cli/run-collection
Execute a collection using a specified data file (CSV or JSON) for variables, overriding the default attached file.
```bash
tc --col 'colNameOrId' --data-file 'relativePathOrFullPath'
```
--------------------------------
### Control Request Output Logging
Source: https://docs.thunderclient.com/cli/run-requests
Customize the output displayed when running a request using the --log argument. Specify log options by number to include specific data like request headers, request body, or response body.
```bash
tc 'welcome' --log 1,2,7
```
--------------------------------
### Basic Assertions without Library
Source: https://docs.thunderclient.com/scripting/assertions
Use this for simple assertions directly within your script. It checks response status and content for specific keywords.
```javascript
let success = tc.response.status == 200;
let json = tc.response.json;
let containsThunder = json.message?.includes("thunder");
tc.test("Response code is 200", success);
tc.test("Response contains thunder word", containsThunder);
// Assertions using function syntax
tc.test("verifying multiple tests", function () {
let success = tc.response.status == 200;
let time = tc.response.time < 1000;
return success && time;
});
```
--------------------------------
### Load Node Module
Source: https://docs.thunderclient.com/scripting/api
Load and access Node.js modules from the npm registry using `tc.loadModule()`. You can specify a version for precise dependency management.
```APIDOC
## Load Node Module
### Description
Load and get a node module from the npm registry. You can specify a version for precise dependency management.
### Methods
* `tc.loadModule(moduleName: string, version?: string): Promise`
* Load and get a node module from the npm registry.
**Sample Usage**
```javascript
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());
```
```
--------------------------------
### Copy Text to Clipboard via Parent Post Message
Source: https://docs.thunderclient.com/testing/chart-view
Demonstrates how to copy text to the clipboard from within an iframe by using `parent.postMessage()` to send a command to the parent window.
```javascript
parent.postMessage({ command: 'copy-text', "text": "textdatatocopy" });
```
--------------------------------
### Run cURL Command with Thunder Client
Source: https://docs.thunderclient.com/cli/curl
Execute a cURL command using the 'tc' prefix to leverage Thunder Client's enhanced features like formatted output and syntax highlighting. This command is a direct replacement for standard cURL commands.
```bash
tc curl 'http://httpbin.org/anything'
```
--------------------------------
### Export Function in JS File
Source: https://docs.thunderclient.com/scripting/import-files
Create a JavaScript file and export functions using `module.exports` to make them available for import in other scripts.
```javascript
// test-import.js file
function helloWorld(){
return "hello world";
}
module.exports = {
helloWorld
}
```
--------------------------------
### Create a New Request from cURL Command
Source: https://docs.thunderclient.com/cli/curl
Create a new request in a specified collection using a cURL command. If the collection does not exist, it will be created automatically. This command also allows you to name the request.
```bash
tc curl 'http://httpbin.org/anything' --name 'Curl Req1' --col 'User'
```
--------------------------------
### Enable VS Code Autocompletion
Source: https://docs.thunderclient.com/scripting/import-files
Copy the `tc-types.d.ts` file to your project and reference it using a `/// ` tag at the top of your script to enable VS Code autocompletion for the `tc` object.
```javascript
// @ts-check
/// copy tc-types.d.ts file for VS Code autocompletion on the tc object
///
```
--------------------------------
### Generate Unix Timestamp
Source: https://docs.thunderclient.com/features/system-variables
Use `{{#date}}` to generate a Unix date timestamp in milliseconds. Use `{{#date, 'X'}}` for seconds. Custom formats and date manipulations are supported.
```text
{{#date}}
{{#date, 'X'}}
{{#date, 'YYYY-MM-DD hh:mm:ss:fff'}}
{{#date, {year: -1, day: 3, mon: 5}}}
{{#date,'YYYY-MM-DD', {year: -1}}}
```
--------------------------------
### Generate Fake Data with Chance
Source: https://docs.thunderclient.com/scripting/libraries
Load and use the chance library to generate random data, such as names. The generated data can be saved to the active environment.
```javascript
// example code to load chance module
var Chance = await tc.loadModule("chance");
var chance = new Chance();
tc.setVar("firstName", chance.name());
```
--------------------------------
### Load Node Module from Local Path
Source: https://docs.thunderclient.com/scripting/libraries
Load a Node module from a specified folder path, useful for private modules or non-npm registries. The path can be relative to the project root or absolute.
```javascript
console.log("load local module");
var moment = tc.loadFromPath("thunder-tests/packages/node_modules/moment");
```
--------------------------------
### Charting
Source: https://docs.thunderclient.com/scripting/api
Function for displaying charts within the ThunderClient interface.
```APIDOC
## Charting
### `tc.chartHTML(template: string, data: any): void`
#### Description
Sets the chart template and data to be displayed. The `template` is an HTML string, and `data` is the data to be visualized. Available since version 2.17.0.
```
--------------------------------
### Import and Use Custom Filter in Inline Script
Source: https://docs.thunderclient.com/scripting/custom-filters
Demonstrates how to import a custom filter JavaScript file and use a function from it within an inline script in Thunder Client's Pre-Request or Post-Request tabs. Ensure the path to the JS file is correct.
```javascript
const [ filterName ] = require("thunder-tests/custom-filters.js");
var result = filterName();
console.log(result);
```
--------------------------------
### Read File from Disk
Source: https://docs.thunderclient.com/scripting/api
Read the content of a file from disk. Supports UTF-8 and Base64 encoding.
```javascript
// To read a text file
await tc.readFile("filePath");
// To read file in base64 encoding
await tc.readFile("filePath", "base64");
```
--------------------------------
### Setting GraphQL Request Body
Source: https://docs.thunderclient.com/scripting/api
Constructs a GraphQL request body, including the query and variables. Specify 'graphql' as the body type.
```javascript
tc.request.setBody({
query: `query {
countries {
name
}
}`,
variables: {
"data": {
"hero": {
"name": "R2-D2"
}
}
}
}, "graphql")
```
--------------------------------
### Command Execution
Source: https://docs.thunderclient.com/scripting/api
Function for executing shell commands.
```APIDOC
## Command Execution
### `tc.exec(command: string): Promise`
#### Description
Executes a given command in the system's shell and returns the result.
```
--------------------------------
### Run Collection for Specific Number of Iterations
Source: https://docs.thunderclient.com/cli/run-collection
Execute a collection a predetermined number of times, overriding the default iteration count.
```bash
tc --col 'colNameOrId' --iterations 10
```
--------------------------------
### Generate Fake Data with Faker-JS
Source: https://docs.thunderclient.com/scripting/libraries
Load and use the faker-js library to generate fake data. The generated data can be saved to the active environment or the request scope.
```javascript
// example code to load faker-js module
var { faker } = await tc.loadModule("@faker-js/faker");
tc.setVar("firstName", faker.person.firstName());
```
```javascript
// to save Env value to Active Environment
tc.setVar("firstName", faker.person.firstName());
// If you do not want to save to the Environment file
// then use the request scope
tc.setVar("firstName", faker.person.firstName(), "request");
```
--------------------------------
### Read File
Source: https://docs.thunderclient.com/scripting/api
Read the content of a file from disk using `tc.readFile()`. Supports specifying encoding like 'utf8' or 'base64'.
```APIDOC
## Read File
### Description
Read a file from disk. Supports specifying encoding like 'utf8' or 'base64'.
### Methods
* `tc.readFile(path: string, encoding?: string): Promise`
* `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**
```javascript
// To read a text file
await tc.readFile("filePath");
// To read file in base64 encoding
await tc.readFile("filePath", "base64");
```
```