### PactumJS Mock Server Startup Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/useRemoteServer.md Demonstrates how to initialize and start a PactumJS mock server, including the definition of a basic interaction handler for a GET request. ```js const { mock, handler } = require('pactum'); handler.addInteractionHandler('get empty users from user-service', () => { return { request: { method: 'GET', path: '/api/users' }, response: { status: 200, body: [] } } }); mock.start(3000); ``` -------------------------------- ### PactumJS Mock Server `start()` Full Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/start.md A complete JavaScript example demonstrating the import of the `pactum` library and the subsequent initiation of the mock server on a custom port (3000) using `await mock.start(3000)`. ```js const { mock } = require('pactum'); await mock.start(3000); ``` -------------------------------- ### JavaScript Full Example: Setting Defaults and Starting Mock Server Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/setDefaults.md A comprehensive JavaScript example demonstrating the complete workflow of requiring PactumJS, setting mock server defaults including HTTPS configuration, and then starting the mock server with the specified options. ```js const pactum = require('pactum'); const mock = pactum.mock; const mockOpts = {port: 3001, host: '127.0.0.1', httpsOpts: {key: "server.key", cert: "server.crt"}}; await mock.setDefaults(mockOpts) await mock.start(); ``` -------------------------------- ### Full Example of addStateHandler with PactumJS Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/handlers/addStateHandler.md Illustrates a complete example of setting up a state handler using the `pactum` library, including requiring necessary modules and starting a mock server. ```js const { mock, handler } = require('pactum'); handler.addStateHandler('some state name', async (ctx) => { const { data } = ctx; // code to add data in database - redis.set() // or code to add mock interactions - mock.addInteraction() // or custom code }); mock.start(3000); ``` -------------------------------- ### PactumJS Basic Mock Interaction Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/addInteraction.md A complete example demonstrating how to add a basic GET mock interaction and start the mock server on port 3000 using PactumJS. ```javascript const { mock } = require('pactum'); mock.addInteraction({ request: { method: 'GET', path: '/api/hello' }, response: { status: 200, body: 'Hello, 👋' } }); mock.start(3000); ``` -------------------------------- ### Install PactumJS and Mocha via npm Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/introduction/quick-start.md This command installs PactumJS and Mocha as development dependencies using npm. PactumJS is a Node.js testing framework, and Mocha is a popular JavaScript test runner often used with PactumJS. ```shell # install pactum npm install -D pactum # install a test runner npm install -D mocha ``` -------------------------------- ### PactumJS withMethod Full Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withMethod.md A complete example demonstrating how to use `withMethod` with a full URL to make a GET request and assert the status. It includes the necessary `require` statement for Pactum. ```javascript const { spec } = require('pactum'); await spec() .withMethod('GET') .withPath('https://reqres.in/api/users/1') .expectStatus(200); ``` -------------------------------- ### PactumJS: removeDefaultHeaders Full Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/settings/removeDefaultHeaders.md A complete example demonstrating setting default headers, then removing a specific header ('key') using `removeDefaultHeaders()`, and finally making an API call to verify the setup. ```js const { spec, request } = require('pactum'); request.setDefaultHeaders({ 'key': 'value', 'key1': 'value1' }); request.removeDefaultHeaders('key'); await spec() .get('https://randomuser.me/api') .expectStatus(200); ``` -------------------------------- ### PactumJS Mock Server `start()` Syntax Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/start.md Illustrates the various ways to invoke the `start` function for the PactumJS mock server, showing options for no arguments, specifying a port, or specifying both port and host. ```js start() start(port) start(port, host) ``` -------------------------------- ### Spec Example: Basic GET Request Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/spec.md A simple example demonstrating how to use `spec()` to make a GET request to a public API and assert the status code. ```js const { spec } = require('pactum'); await spec() .get('https://reqres.in/api/users/1') .expectStatus(200); ``` -------------------------------- ### PactumJS Mock Server `start()` Arguments Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/start.md Defines the parameters accepted by the `start` function of the PactumJS mock server, including `port` (number) and `host` (string), along with their descriptions and default values. ```APIDOC port (number) port number host (string) host. defaults to localhost. ``` -------------------------------- ### PactumJS Flow Method Full Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/flow.md Provides a complete example of using the `flow` method, including its import. It performs a GET request to an external API and asserts the HTTP status code. ```js const { flow } = require('pactum'); await flow('get a user') .get('https://reqres.in/api/users/1') .expectStatus(200); ``` -------------------------------- ### PactumJS Mock Server Start Default Port Usage Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/start.md Demonstrates how to start the PactumJS mock server on its default port (9393) using the `await mock.start()` method without any arguments. ```js // starts on default port 9393 await mock.start(); ``` -------------------------------- ### PactumJS Example: Add Multiple Headers Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withHeaders.md Complete examples showing two ways to add multiple headers ('Authorization' and 'Accept') to a PactumJS GET request: chaining `withHeaders` calls or providing an object. ```javascript const { spec } = require('pactum'); await spec() .get('https://httpbin.org/bearer') .withHeaders('Authorization', 'Bearer abc') .withHeaders('Accept', 'application/json') .expectStatus(200); ``` ```javascript await spec() .get('https://httpbin.org/bearer') .withHeaders({ 'Authorization': 'Bearer abc', 'Accept': 'application/json' }) .expectStatus(200); ``` -------------------------------- ### PactumJS setBaseUrl Normal Usage Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/settings/setBaseUrl.md A comprehensive example demonstrating the typical use of `setBaseUrl` to configure a base URL for API requests, followed by a GET request to a relative path. ```js const { spec, request } = require('pactum'); request.setBaseUrl('https://reqres.in'); await spec() .get('/api/users/1') .expectStatus(200); ``` -------------------------------- ### Install PactumJS dependencies Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/README.md This command installs all necessary project dependencies using npm. ```sh npm i ``` -------------------------------- ### PactumJS: Basic File Upload Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withFile.md A complete example demonstrating a basic file upload to `httpbin.org` using `withFile` with just the file path. ```javascript const { spec } = require('pactum'); await spec() .post('https://httpbin.org/forms/posts') .withFile('./path/to/the/file') .expectStatus(201); ``` -------------------------------- ### Start PactumJS Mock Server Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/guides/mock-server.md This snippet demonstrates how to start the PactumJS mock server using `mock.start()`. It runs the server on the specified port, making it ready to receive requests. It's encouraged to use `mock.setDefaults()` for initial configuration. ```js const { mock } = require('pactum'); // runs mock server on port 3000 await mock.start(3000); ``` -------------------------------- ### Correct Usage Examples for findFile Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/utils/findFile.md Provides practical examples demonstrating the correct invocation of the `findFile` function with a file name and an optional search path. ```javascript findFile('file.txt'); findFile('file.txt', 'path/to/the/dir'); ``` -------------------------------- ### PactumJS withPath Example - Without BaseUrl Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withPath.md Provides a complete example of using `withPath` with a full URL when no `baseUrl` is configured, demonstrating a successful GET request to retrieve user data. ```js const { spec } = require('pactum'); await spec() .withMethod('GET') .withPath('https://reqres.in/api/users/1') .expectStatus(200); ``` -------------------------------- ### PactumJS Mock Server Start Custom Port Usage Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/start.md Shows how to start the PactumJS mock server on a specific port, such as 3000, by passing the port number as an argument to `await mock.start(3000)`. ```js // starts on specified port await mock.start(3000); ``` -------------------------------- ### PactumJS: Example of updateSnapshot() for GET User API Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/assertions/updateSnapshot.md A comprehensive example showcasing the use of `updateSnapshot` in a PactumJS test, including path parameters, status assertion, and `expectJsonSnapshot` for a GET request to update user data snapshots. ```js const { spec } = require('pactum'); const { like } = require('pactum-matchers'); await spec() .name('GET_User_Mark') .get('https://some-api/user/{username}') .withPathParams('username', 'Mark') .expectStatus(200) .expectJsonSnapshot({ id: like(123) }) .updateSnapshot(); ``` -------------------------------- ### Initialize PactumJS project using npx Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/introduction/quick-start.md This command uses npx to run the pactum-init script, which helps set up a new PactumJS project quickly. ```shell npx pactum-init ``` -------------------------------- ### PactumJS: Example of Setting Default Headers and Making a Request Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/settings/setDefaultHeaders.md A complete example showing how to use `setDefaultHeaders` to set a default header and then make an HTTP GET request using PactumJS, expecting a 200 status. ```js const { spec, request } = require('pactum'); request.setDefaultHeaders({ 'key': 'value' }); await spec() .get('https://randomuser.me/api') .expectStatus(200); ``` -------------------------------- ### Install Pactum JSON Reporter Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/guides/reporting.md Installs the `pactum-json-reporter` package as a development dependency using npm. ```shell npm install --save-dev pactum-json-reporter ``` -------------------------------- ### Write a basic PactumJS test with Mocha Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/introduction/quick-start.md This JavaScript code snippet demonstrates a simple PactumJS test integrated with Mocha. It uses `spec()` to define a test that makes a GET request to `http://httpbin.org/status/200` and asserts that the response status code is 200. ```js // test.js const { spec } = require('pactum'); it('should get a response with status code 200', async () => { await spec() .get('http://httpbin.org/status/200') .expectStatus(200); }); ``` -------------------------------- ### PactumJS Bearer Authentication Full Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withBearerToken.md Provides a complete example demonstrating bearer authentication using PactumJS. It shows how to import `spec`, make a GET request to an external API with a bearer token, and verify the successful response. ```js const { spec } = require('pactum'); await spec() .get('https://httpbin.org/bearer') .withBearerToken('my-token') .expectStatus(200); ``` -------------------------------- ### Run PactumJS documentation server Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/README.md This command starts the local development server for the PactumJS documentation. The documentation will be accessible via http://localhost:5173. ```sh npm run docs:dev ``` -------------------------------- ### PactumJS withPath Example - With BaseUrl Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withPath.md Illustrates how to use `withPath` with a relative path after setting a `baseUrl`, showcasing a successful GET request to retrieve user data and demonstrating efficient URL management. ```js const { spec, request } = require('pactum'); request.setBaseUrl('https://reqres.in'); await spec() .withMethod('GET') .withPath('/api/users/1') .expectStatus(200); ``` -------------------------------- ### Full Example: Setting a Custom Logger with PactumJS Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/settings/setLogger.md Provides a complete example of defining a custom logger object and then applying it to PactumJS settings using `settings.setLogger`. ```js const { settings } = require('pactum'); const myCustomLogger = { trace(messages) { /* custom code */ }, debug(messages) { /* custom code */ }, info(messages) { /* custom code */ }, warn(messages) { /* custom code */ }, error(messages) { /* custom code */ } }; settings.setLogger(myCustomLogger); ``` -------------------------------- ### Run tests using npm script Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/introduction/quick-start.md This shell command executes the 'test' script defined in `package.json`, which in turn runs the Mocha tests. ```shell npm run test ``` -------------------------------- ### PactumJS Basic Authentication Correct Usage Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withAuth.md Demonstrates the standard application of `withAuth` within a PactumJS test spec. It shows how to chain `withAuth` after a GET request to apply basic authentication and then assert a 200 status code. ```js await spec() .get('/api/users') .withAuth('my-username', 'super-secret-password') .expectStatus(200); ``` -------------------------------- ### PactumJS: Full example using name() for API testing Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/name.md Provides a comprehensive example demonstrating the `name()` method in a typical PactumJS API test. It includes requiring the `spec` object, setting a test name, performing a GET request to an external API, and asserting the HTTP status code. This showcases end-to-end usage. ```js const { spec } = require('pactum'); await spec() .name('get a user') .get('https://reqres.in/api/users/1') .expectStatus(200); ``` -------------------------------- ### PactumJS Basic Authentication Full Example with httpbin Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withAuth.md Provides a complete, runnable example of using `withAuth` for basic authentication. This snippet includes importing `spec` from PactumJS and making a request to `httpbin.org` to verify authentication, expecting a 200 status. ```js const { spec } = require('pactum'); await spec() .get('https://httpbin.org/basic-auth/user/pass') .withAuth('user', 'pass') .expectStatus(200); ``` -------------------------------- ### PactumJS: Full example of stopping the mock server Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/stop.md Provides a complete example showing how to import the mock object from 'pactum' and then stop the mock server using await. ```js const { mock } = require('pactum'); await mock.stop(); ``` -------------------------------- ### Example of Correct setCaptureHandlerStrategy Usage Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/settings/setCaptureHandlerStrategy.md Demonstrates a simple and correct way to use `setCaptureHandlerStrategy` by configuring capture handlers to start with '##'. ```js setCaptureHandlerStrategy({ starts: '##' }); ``` -------------------------------- ### Example JSON Payload for User Creation Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/guides/data-management.md An example of a JSON payload used to create a new user via a HTTP POST request to the /api/users endpoint. ```JSON { "FirstName": "Jon", "LastName": "Snow", "Age": 26 } ``` -------------------------------- ### Complete E2E test example with Pactum.js (Create, Read, Delete) Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/guides/e2e-testing.md This example demonstrates a simple end-to-end test flow: - Create a new user. - Validate the newly created user. - Delete the user at the end using cleanup. ```javascript const { e2e } = require('pactum'); describe('AddUser_ReadUser', () => { let test_case = e2e('Add User'); it('create user', async () => { await test_case.step('Post User') .spec() .post('/api/users') .withJson({ "name": "snow" }) .expectStatus(200) .clean() .delete('/api/users/snow') .expectStatus(200); }); it('get user', async () => { await test_case.step('Get User') .spec() .get('/api/users/snow') .expectStatus(200) .expectJson({ "name": "snow" }); }); it('clean up', async () => { // runs all registered cleanup methods in LIFO order await test_case.cleanup(); }); }); ``` -------------------------------- ### PactumJS setLogLevel Full Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/settings/setLogLevel.md A complete example showing how to import PactumJS settings and set the log level to 'ERROR'. ```javascript const { settings } = require('pactum'); settings.setLogLevel('ERROR'); ``` -------------------------------- ### PactumJS End-to-End getInteraction Example with Mock Setup Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/getInteraction.md A comprehensive example showcasing the full workflow of using `getInteraction` in PactumJS. It first adds a mock interaction to the server and then retrieves it using the generated ID, demonstrating a common testing scenario. ```js const { mock } = require('pactum'); const id = mock.addInteraction({ request: { method: 'GET', path: '/api/hello' }, response: { status: 200, body: 'Hello, 👋' } }); const interaction = mock.getInteraction(id); ``` -------------------------------- ### PactumJS Example: Single Query Parameter Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withQueryParams.md A practical example demonstrating how to use `withQueryParams` to add a single query parameter ('gender', 'male') to a GET request to `https://randomuser.me/api` and assert a 200 status. ```js const { spec } = require('pactum'); await spec() .get('https://randomuser.me/api') .withQueryParams('gender', 'male') .expectStatus(200); ``` -------------------------------- ### Full example: Define and use an empty users interaction handler in PactumJS Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/handlers/addInteractionHandler.md A complete example showing how to define an interaction handler for empty users and then add it to the mock server using `mock.addInteraction`. It includes the necessary `require` statements and starting the mock server. ```js const { handler, mock } = require('pactum'); handler.addInteractionHandler('get empty users from user-service', () => { return { request: { method: 'GET', path: '/api/users' }, response: { status: 200, body: [] } } }); mock.addInteraction('get users from user-service'); mock.start(3000); ``` -------------------------------- ### PactumJS Example: Multiple Query Parameters Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withQueryParams.md Provides two ways to add multiple query parameters to a GET request: chaining `withQueryParams` calls for individual parameters, or using a single call with an object containing all parameters. Both examples target `https://randomuser.me/api` and expect a 200 status. ```js const { spec } = require('pactum'); await spec() .get('https://randomuser.me/api') .withQueryParams('gender', 'male') .withQueryParams('nat', 'AU') .expectStatus(200); ``` ```js // or await spec() .get('https://randomuser.me/api') .withQueryParams({ 'gender', 'male', 'nat': 'AU' }) .expectStatus(200); ``` -------------------------------- ### PactumJS: setDataDirectory Full Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/settings/setDataDirectory.md A complete JavaScript example demonstrating how to import the `settings` object from `pactum` and then use `setDataDirectory` to change the data storage location. ```js const { settings } = require('pactum'); settings.setDataDirectory('new/path'); ``` -------------------------------- ### JavaScript Usage: Setting Mock Server Port and Host Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/setDefaults.md Demonstrates how to use `setDefaults` in JavaScript to configure the mock server's port and optionally its hostname. These examples show basic setup for HTTP mock servers. ```js // set port mock.setDefaults({port: 3000}); ``` ```js // set port and hostname mock.setDefaults({port: 3000, host: '127.0.0.1'}); ``` -------------------------------- ### PactumJS save function full example with HTTP GET and status check Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/save.md A complete example of using the `save` function with PactumJS to download an image from a URL and save it to a local file, including `expectStatus` for verification. ```js const { spec } = require('pactum'); await spec() .get('https://httpbin.org/image/png') .save('pig.png') .expectStatus(200); ``` -------------------------------- ### PactumJS: Example Setting Default Response Time for API Test Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/responses/setDefaultExpectResponseTime.md A comprehensive example demonstrating how to set a global default response time using `setDefaultExpectResponseTime` before making an API GET request. The example then asserts the HTTP status code, implicitly using the configured default response time for any response time checks. ```js const { spec, response } = require('pactum'); response.setDefaultExpectResponseTime(2000) await spec() .get('https://randomuser.me/api') .expectStatus(200); ``` -------------------------------- ### Correct Usage Examples for setState Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/setState.md Illustrates valid invocations of the `setState` function, showing how to call it with just a name or with additional data. ```js setState('admin user'); setState('admin user', { data: 'some data' }); ``` -------------------------------- ### PactumJS returns() example: Using capture handlers Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/returns.md Full example demonstrating how to define and use a custom capture handler with returns() for reusable data extraction logic. ```js const { spec, handler } = require('pactum'); handler.addCaptureHandler('first post id', (ctx) => { return ctx.res.json[0].id; }); const postID = await spec() .get('http://jsonplaceholder.typicode.com/posts') .expectStatus(200) .returns('#first post id'); ``` -------------------------------- ### PactumJS withBody File Upload Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withBody.md A complete example demonstrating uploading a file by path using `withBody` to a public API and asserting the status. ```js const { spec } = require('pactum'); await spec() .post('https://httpbin.org/anything') .withBody({ file: "path/to/file" }) .expectStatus(200); ``` -------------------------------- ### PactumJS: Full Example with `setSnapshotDirectoryPath` and `expectJsonSnapshot` Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/settings/setSnapshotDirectoryPath.md A comprehensive example showing how to configure the snapshot directory using `settings.setSnapshotDirectoryPath` before making an API call and asserting the JSON response against a snapshot using `expectJsonSnapshot`. This ensures tests use the specified directory for snapshot files. ```js const { spec, settings } = require('pactum'); settings.setSnapshotDirectoryPath('new/path'); await spec() .name('snapshot directory test') .get('/api/users/1') .expectStatus(200) .expectJsonSnapshot(); ``` -------------------------------- ### eachLike Mock Server Interaction (Multiple Items) Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/matching/eachLike.md Example of configuring a PactumJS mock server interaction using `eachLike` with the `items` option to return multiple custom elements in an array for a GET request to `/api/users`. ```js const { mock } = require('pactum'); const { eachLike } = require('pactum-matchers'); // return multiple users - dad and brother mock.addInteraction({ request: { method: 'GET', path: '/api/users' }, response: { status: 200, body: eachLike({ "name": "mom", "age": 50 }, items: [ { "name": "dad", "age": 55 }, { "name": "brother", "age": 30 } ]) } }); ``` -------------------------------- ### PactumJS: Basic JSON Snapshot Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/assertions/expectJsonSnapshot.md A complete example demonstrating a straightforward JSON snapshot test for an API endpoint. This snippet shows how to fetch data and then use `expectJsonSnapshot()` to either create a new snapshot or compare against an existing one. ```js const { spec } = require('pactum'); await spec() .name('get first user') .get('https://reqres.in/api/users/1') .expectJsonSnapshot(); ``` -------------------------------- ### PactumJS Example: Add Single Authorization Header Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withHeaders.md A complete example demonstrating how to add a single 'Authorization' header to a PactumJS GET request and assert the status. ```javascript const { spec } = require('pactum'); await spec() .get('https://httpbin.org/bearer') .withHeaders('Authorization', 'Bearer abc') .expectStatus(200); ``` -------------------------------- ### PactumJS: Complete Example for Response Time Assertion Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/assertions/expectResponseTime.md A comprehensive example showing how to import PactumJS and assert the response time of an external API call using `expectResponseTime`. ```js const { spec } = require('pactum'); await spec() .get('https://reqres.in/api/users/1') .expectResponseTime(1500); ``` -------------------------------- ### PactumJS use() Method Correct Usage Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/use.md Example demonstrating how to apply a spec handler using `use()` within a PactumJS spec and then assert on the response. ```js await spec() .use('get user') .expectJson('data.first_name', 'George'); ``` -------------------------------- ### expectBodyContains Real-World Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/assertions/expectBodyContains.md Provides a practical example of expectBodyContains asserting content from an external robots.txt file. ```javascript const { spec } = require('pactum'); await spec() .get('https://httpbin.org/robots.txt') .expectBodyContains(`User-agent: *`); ``` -------------------------------- ### Start PactumJS Mock Server for Remote API Control Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/guides/mock-server.md Initializes and starts the PactumJS mock server on port 3000, making it accessible for remote control via its REST API. This is a prerequisite for using the remote API features. ```javascript const { mock } = require('pactum'); mock.start(3000); ``` -------------------------------- ### PactumJS: Complete expectHeaderContains Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/assertions/expectHeaderContains.md Provides a comprehensive example demonstrating the use of `expectHeaderContains` with `pactum` to assert a partial content-type header from a live API endpoint. ```javascript const { spec } = require('pactum'); await spec() .get('https://reqres.in/api/users') .expectHeaderContains('content-type', 'application/json'); ``` -------------------------------- ### PactumJS: `withRequestTimeout` Normal Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withRequestTimeout.md Provides a standard example of using `withRequestTimeout` with a GET request to an external API, ensuring the request completes within the specified 5000ms timeout. ```js const { spec } = require('pactum'); await spec() .get('https://reqres.in/api/users/1') .expectStatus(200) .withRequestTimeout(5000); ``` -------------------------------- ### PactumJS Spec Handler Definition and Multiple use() Examples Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/use.md Comprehensive example showing how to define a custom spec handler with `handler.addSpecHandler` and then use it multiple times with `use()`, including passing data. ```js const { spec, handler } = require('pactum'); handler.addSpecHandler('get user', () => { const { spec, data } = ctx; spec.get('https://reqres.in/api/users/{id}'); spec.withPathParams('id', data || 1) spec.expectStatus(200); }); await spec().use('get user').expectJson('data.first_name', 'George'); await spec().use('get user', 2).expectJson('data.first_name', 'Janet'); ``` -------------------------------- ### PactumJS withBody XML Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withBody.md A complete example demonstrating sending an XML string body to a public API using `withBody` and asserting the status. ```js const { spec } = require('pactum'); await spec() .post('https://reqbin.com/echo/post/xml') .withBody(` login password `) .expectStatus(200); ``` -------------------------------- ### Configure package.json script for Mocha tests Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/introduction/quick-start.md This JSON snippet shows how to add a 'test' script to your `package.json` file. This script uses Mocha to run the `test.js` file, allowing you to execute your tests using `npm run test`. ```json { "scripts": { "test": "mocha test.js" } } ``` -------------------------------- ### PactumJS withCookies Full Key-Value Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withCookies.md A complete example demonstrating how to use the `withCookies` function to set a single key-value pair cookie and verify the request status against `httpbin.org`. ```js const { spec } = require('pactum'); await spec() .get('https://httpbin.org/cookies') .withCookies('user', 'pass') .expectStatus(200); ``` -------------------------------- ### Example cURL Command for Data Post Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/tools/converter.md Demonstrates a cURL command to send a POST request with JSON data and custom headers to an example API endpoint. ```bash curl -X POST "https://api.example.com/data" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer token123" \ --data '{\"key\": \"value\"}' ``` -------------------------------- ### End-to-End Example: loadData() with API Request Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/stash/loadData.md A comprehensive example showing how `stash.loadData()` is used to load data, followed by an API POST request. The example demonstrates how loaded data maps (e.g., `User.name`, `User.job`) can be seamlessly integrated into the request payload using PactumJS's `$M{}` syntax. ```js const { stash, spec } = require('pactum'); stash.loadData(); await spec() .post('https://reqres.in/api/users') .withJson({ "name": "$M{User.name}", "job": "$M{User.job}" }); ``` -------------------------------- ### PactumJS: File Upload with Custom Options Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withFile.md An example showing how to upload a file with a custom form field key and explicit `contentType` using `withFile`. ```javascript const { spec } = require('pactum'); await spec() .post('https://httpbin.org/forms/posts') .withFile('file-image', './path/to/the/file', { contentType: 'image/png' }) .expectStatus(201); ``` -------------------------------- ### Includes Matcher Correct Usage Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/matching/includes.md Demonstrates a simple correct usage of the `includes` matcher. ```js includes('some') ``` -------------------------------- ### PactumJS withBody JSON Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withBody.md A complete example demonstrating sending a JSON string body to a public API using `withBody` and asserting the status. ```js const { spec } = require('pactum'); await spec() .post('https://reqres.in/api/users') .withBody(` { "name": "morpheus", "job": "leader" } `) .expectStatus(201); ``` -------------------------------- ### Example: Data Function Handlers with Custom Arguments Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/handlers/addDataFuncHandler.md Demonstrates how to define and use data function handlers that accept custom arguments, showing 'GetFormattedDate' and 'GetSum' examples. ```js const { handler, spec } = require('pactum'); const moment = require('moment'); handler.addDataFuncHandler('GetFormattedDate', (ctx) => { const fmt = ctx.args[0]; return moment.format(fmt); }); handler.addDataFuncHandler('GetSum', (ctx) => { const a = parseInt(ctx.args[0]); const b = parseInt(ctx.args[1]); return a + b; }); await spec() .post('/api/order') .withJson({ 'Item': 'Sword', 'CreatedAt': '$F{GetFormattedDate:dddd}', 'Qty': '$F{GetSum:5,10}' }); ``` -------------------------------- ### PactumJS withForm Full Example with External API Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withForm.md Provides a complete example of using `withForm` with PactumJS to send form data to an external public endpoint (httpbin.org). This example includes the `require` statement for `spec` and demonstrates sending user credentials while expecting a 201 status. ```js const { spec } = require('pactum'); await spec() .post('https://httpbin.org/forms/posts') .withForm({ "user": 'jon', "password": 'abc' }) .expectStatus(201); ``` -------------------------------- ### PactumJS records() - Full Example Recording a Custom Object Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/records.md A comprehensive example showing how to record an entire custom JavaScript object and then retrieve and print it within a custom reporter's `afterSpec` method. ```js const { spec, reporter } = require('pactum'); const custom_reporter = { afterSpec(spec) { // prints - { message: { value: 'hi mom' } } console.log(spec.recorded); } } reporter.add(custom_reporter); const postID = await spec() .get('http://jsonplaceholder.typicode.com/posts') .expectStatus(200) .records('message', { value: 'hi mom' }); ``` -------------------------------- ### PactumJS: Basic JSON Schema Validation Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/assertions/expectJsonSchema.md Shows a complete example of using `expectJsonSchema` with `pactum` to validate a GET request's response body against a JSON schema, including required imports. ```js const { spec } = require('pactum'); const { like } = require('pactum-matchers'); await spec() .get('https://reqres.in/api/users/1') .expectJsonSchema({ "type": "object" }); ``` -------------------------------- ### Example: Adding Custom Expect Handler and Setting Default Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/responses/setDefaultExpectHandlers.md A comprehensive example demonstrating how to define a custom expect handler using `handler.addExpectHandler` and then set it as a default for all subsequent response assertions using `response.setDefaultExpectHandlers`. The example includes an API call to 'https://randomuser.me/api' and an assertion based on the custom handler. ```js const { handler, spec, response } = require('pactum'); const { expect } = require("chai") handler.addExpectHandler('user', (ctx) => { // ctx.data will have 'gender' expect(ctx.res.json.results[0]).to.have.property(ctx.data); }); response.setDefaultExpectHandlers('user', 'gender') await spec() .get('https://randomuser.me/api') .expectStatus(200); ``` -------------------------------- ### PactumJS: `useLogLevel` Examples and Default Log Level Behavior Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/useLogLevel.md Provides examples of setting a specific log level ('DEBUG') for one spec. It also illustrates that subsequent specs without `useLogLevel` will revert to the default 'INFO' log level, demonstrating its per-spec application. ```js const { spec } = require('pactum'); await spec() .get('https://reqres.in/api/users/1') .expectStatus(200) .useLogLevel('DEBUG'); // the below spec will have the default log level - 'INFO' await spec() .get('https://reqres.in/api/users/1') .expectStatus(200); ``` -------------------------------- ### PactumJS stores Method Arguments Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/stores.md Detailed documentation for the parameters accepted by the `stores` method, including their types, descriptions, and special considerations like `path` prefixes and `options`. ```APIDOC stores(name: string, path: string, options?: object) stores(name: string, handler_name: string, options?: object) stores(callback_function: (request: Request, response: IncomingMessage & {body: Record, json: Record}) => T) Parameters: - name (string): Name of the variable to store the data under. - path (string): JSON path to extract data from the response. Special prefixes include: - req.pathParams: Request path parameters - req.queryParams: Request query parameters - req.headers: Request headers - req.cookies: Request cookies - res.body: Response body (default) - res.headers: Response headers - res.cookies: Response cookies - handler_name (string): Name of a registered capture handler to process the response. - callback_function (function): A custom function that receives the request and response objects and returns an object to be stored. - options (object, optional): Configuration options for the store operation: - status (string, optional): Specifies when to run the handler. Can be 'PASSED' or 'FAILED'. - append (boolean, optional): If true, appends the stored data to an array under the variable name. - merge (boolean, optional): If true, merges the stored data into a single object under the variable name. ``` -------------------------------- ### PactumJS: Example Setting Default Expect Status Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/responses/setDefaultExpectStatus.md A comprehensive example showing how to import PactumJS modules, set a default expected HTTP status code (200) for responses, and then perform a GET request to an API endpoint. ```js const { spec, response } = require('pactum'); response.setDefaultExpectStatus(200) await spec() .get('https://randomuser.me/api'); ``` -------------------------------- ### PactumJS: Full Example Setting Single Default Expect Header Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/responses/setDefaultExpectHeaders.md A complete example demonstrating how to use `setDefaultExpectHeaders` with a key-value pair in PactumJS. It sets a default 'content-type' header and then performs a GET request, asserting the status. ```javascript const { spec, response } = require('pactum'); response.setDefaultExpectHeaders('content-type', 'application/json') await spec() .get('https://randomuser.me/api') .expectStatus(200); ``` -------------------------------- ### PactumJS use() Method Arguments Reference Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/use.md API documentation for the arguments accepted by the `use` method. ```APIDOC handler-name (string): Name of the spec handler to use. ``` -------------------------------- ### Example: Normal Usage of Data Function Handlers Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/handlers/addDataFuncHandler.md Full example demonstrating the definition of 'GetTimeStamp' and 'GetAuthToken' handlers and their usage within a PactumJS `spec` for headers and JSON body. ```js const { handler, spec } = require('pactum'); handler.addDataFuncHandler('GetTimeStamp', () => { return Date.now(); }); handler.addDataFuncHandler('GetAuthToken', () => { return 'Basic some-token'; }); await spec() .post('/api/order') .withHeaders('Authorization', '$F{GetAuthToken}') .withJson({ 'Item': 'Sword', 'CreatedAt': '$F{GetTimeStamp}' }); ``` -------------------------------- ### PactumJS inspect() basic usage example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/inspect.md Demonstrates the simplest form of `inspect()` to print all request and response details for debugging purposes. ```js await spec() .get('/api/users/1') .inspect(); ``` -------------------------------- ### PactumJS withCore Method Syntax Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withCore.md Shows the basic syntax for the `withCore` method in PactumJS. ```js withCore(options) ``` -------------------------------- ### PactumJS lte Matcher Basic Usage Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/matching/lte.md Demonstrates a straightforward example of using the `lte` matcher with a specific numeric input. This snippet shows how to pass a constant value for comparison. ```js // with custom input lte(10); ``` -------------------------------- ### PactumJS: Full Example of expectHeader Usage Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/assertions/expectHeader.md Provides a complete example of using `expectHeader` with `require('pactum')` to assert a specific 'content-type' header, including charset, from an external API. ```js const { spec } = require('pactum'); await spec() .get('https://reqres.in/api/users') .expectHeader('content-type', 'application/json; charset=utf-8'); ``` -------------------------------- ### PactumJS: Full Example Setting Multiple Default Expect Headers Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/responses/setDefaultExpectHeaders.md A comprehensive example showing how to use `setDefaultExpectHeaders` with an object in PactumJS. It sets multiple default headers ('content-type', 'connection') and then executes a GET request, asserting the status. ```javascript const { spec, response } = require('pactum'); response.setDefaultExpectHeaders({ 'content-type': 'application/json', 'connection': 'keep-alive' }) await spec() .get('https://randomuser.me/api') .expectStatus(200); ``` -------------------------------- ### PactumJS returns() example: Extract multiple values Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/returns.md Full example showing how to extract multiple post IDs using chained returns() calls and then use them in subsequent requests. ```js const { spec } = require('pactum'); const ids = await spec() .get('http://jsonplaceholder.typicode.com/posts') .expectStatus(200) .returns('[0].id') .returns('[1].id'); await spec() .get(`http://jsonplaceholder.typicode.com/posts/${ids[0]}/comments`) .expectStatus(200); await spec() .get(`http://jsonplaceholder.typicode.com/posts/${ids[1]}/comments`) .expectStatus(200); ``` -------------------------------- ### PactumJS Remote Mock Server Control Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/mock/useRemoteServer.md Shows how to connect to and manage a remote PactumJS mock server from a separate file, adding new interactions and reusing existing ones. ```js const { mock } = require('pactum'); mock.useRemoteServer('http://localhost:3000'); await mock.addInteraction({ request: { method: 'GET', path: '/api/hello' }, response: { status: 200, body: 'Hello, 👋' } }); await mock.addInteraction('get empty users from user-service'); ``` -------------------------------- ### Example: Retrieving Data Store After API Call (PactumJS) Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/stash/getDataStore.md Provides a comprehensive example showing how to use `getDataStore()` to access data previously stored from an API response within a PactumJS test specification. ```javascript const { stash, spec } = require('pactum'); await spec() .get('https://reqres.in/api/users/1') .stores('Email', 'data.email'); const data_store = stash.getDataStore(); ``` -------------------------------- ### PactumJS records() - Full Example Using Capture Handlers Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/records.md An end-to-end example demonstrating the use of capture handlers with `records()`. It defines a custom handler, adds it, and then uses it to record a value, which is subsequently accessed in a custom reporter. ```js const { spec, handler, reporter } = require('pactum'); const custom_reporter = { afterSpec(spec) { // prints - { first_id: 1 } console.log(spec.recorded); } } reporter.add(custom_reporter); handler.addCaptureHandler('first post id', (ctx) => { return ctx.res.json[0].id; }); const postID = await spec() .get('http://jsonplaceholder.typicode.com/posts') .expectStatus(200) .records('first_id', '#first post id'); ``` -------------------------------- ### onSwagger Correct Usage Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/fuzz/onSwagger.md Provides an example of correctly using the `onSwagger` function with `fuzz()` to generate requests from a specified Swagger JSON endpoint, demonstrating its application in an asynchronous context. ```js // url to the swagger json await fuzz() .onSwagger('/api/swagger.json'); ``` -------------------------------- ### Define interaction handlers that reuse other handlers in PactumJS Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/handlers/addInteractionHandler.md Illustrates how interaction handlers can refer to and reuse other previously defined handlers. This example defines a generic 'get product' handler and then two specific handlers ('get product in stock', 'get product out of stock') that call the generic one with different data, promoting modularity and reducing duplication. ```js const { mock, handler } = require('pactum'); handler.addInteractionHandler('get product', (ctx) => { return { request: { method: 'GET', path: '/api/inventory', queryParams: { product: ctx.data.product } }, response: { status: 200, body: { "InStock": ctx.data.inStock } } } }); handler.addInteractionHandler('get product in stock', () => { // reuses the above interaction return { name: 'get product', data: { product: 'iPhone', inStock: true } }; }); handler.addInteractionHandler('get product out of stock', () => { // reuses the first interaction return { name: 'get product', data: { product: 'iPhone', inStock: false } }; }); mock.addInteraction('get product in stock'); mock.addInteraction('get product out of stock'); mock.start(3000); ``` -------------------------------- ### PactumJS toss() Method Full Example with Assertions Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/toss.md Provides a comprehensive example of using `toss()` to execute an API request, capture the response, and perform detailed assertions on its status and JSON content using PactumJS's `expect` and `response` methods. ```javascript const { spec, expect } = require('pactum'); const _spec = spec(); _spec.get('https://reqres.in/api/users/1') const response = await _spec.toss(); expect(response).to.have.status(200); _spec.response().to.have.jsonLike({ "data": { "first_name": "George" } }); ``` -------------------------------- ### expectBodyContains Basic Usage Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/assertions/expectBodyContains.md Demonstrates how to use expectBodyContains to assert partial body content in a simple GET request. ```javascript await spec() .get('/api/health') .expectBodyContains('OK'); ``` -------------------------------- ### PactumJS: Example - Sending Multipart Form Data with Key-Value Pairs Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/requests/withMultiPartFormData.md A complete example demonstrating how to send multipart form data using key-value pairs with PactumJS, including the `require` statement and a full URL for the POST request. ```js const { spec } = require('pactum'); await spec() .post('https://httpbin.org/forms/posts') .withMultiPartFormData('file', fs.readFileSync('a.txt'), { filename: 'a.txt' }) .expectStatus(201); ``` -------------------------------- ### Fuzz Instance Creation Syntax Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/fuzz/fuzz.md Shows the basic syntax for creating a fuzz instance. ```js fuzz() ``` -------------------------------- ### PactumJS: Make a GET Request to Fetch Random Users Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/guides/api-testing.md Demonstrates how to use the `spec()` method with `.get()` to perform a basic HTTP GET request to fetch a list of random users from an API endpoint. ```js const { spec } = require('pactum'); it('should get random users', async () => { await spec() .get('https://randomuser.me/api'); }); ``` -------------------------------- ### PactumJS: Example Setting Default Follow Redirects to True Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/settings/setDefaultFollowRedirects.md A complete example demonstrating how to set default follow redirects to true and make a request that follows a redirect to a 200 status. ```js const { spec, request } = require('pactum'); request.setDefaultFollowRedirects(true); await spec() .get('https://httpbin.org/redirect-to') .withQueryParams('url', 'https://httpbin.org/status/200') .expectStatus(200); ``` -------------------------------- ### Full Example: Configure Request Retries with PactumJS (JavaScript) Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/settings/setRequestDefaultRetryCount.md Provides a comprehensive example showing the integration of `setRequestDefaultRetryCount` within a PactumJS test. It sets the default retry count to 2 and then performs a GET request, which will automatically retry if the initial attempt fails. ```javascript const { spec, settings } = require('pactum'); settings.setRequestDefaultRetryCount(2); await spec() .get('https://randomuser.me/api') .expectStatus(200); ``` -------------------------------- ### PactumJS: addSpecHandler Normal Usage Example Source: https://github.com/pactumjs/pactumjs.github.io/blob/main/docs/api/handlers/addSpecHandler.md This example illustrates how to define and use a spec handler for fetching a random user. It shows the handler definition using `handler.addSpecHandler` and its subsequent invocation with `await spec('get random user')`, including response validation. ```js const { handler, spec } = require('pactum'); handler.addSpecHandler('get random user', (ctx) => { const { spec } = ctx; spec.get('https://randomuser.me/api'); spec.expectStatus(200); }); await spec('get random user') .expectJsonLike({ "results": [ { "dob": { "age": '$V > 0' } } ] }); ```