mablでは、1つ以上のAPIスニペットを組み合わせてAPIテストのカスタムスクリプトを作成できます。アサーションや変数を作成する際には、できるだけmablのローコード機能を使用することをお勧めします。カスタムスニペットの使用を複雑なシナリオに限定することで、ワークスペースのすべてのメンバーがテスト結果を容易に表示し、保守できるようになります。
この記事では、APIスニペット内でいくつかの一般的なタスクを実行する方法について説明します。
次に示す例の多くは、Postman JavaScriptオブジェクトを利用しています。このオブジェクトは、mablとPostmanとのインテグレーションにより使用できます。
XMLペイロードの使用
XML ペイロードを使用する API を扱う場合は、詳細について XML ペイロードの操作に関する記事を参照してください。
変数へのアクセス
APIスニペットでテストの既存の変数を使用するには、pm.variables.get()を使用します。例:
// get the value of "new_user_id" and store in variable newUserId
let newUserId = pm.variables.get("new_user_id")
// log the value of newUserId to the console
console.log(`The new user's ID is ${newUserId}`);スニペット内でフローパラメータにアクセスするには、pm.variables.replaceIn()を使用します。例:
// get the value of "product_id" flow parameter and store in variable productId
let productId = pm.variables.replaceIn('{{flow.product_id}}')
// log the value of newUserId to the console
console.log(`The product ID is ${productId}`);レスポンスの検証
JSON ボディレスポンスを検証するには、pm.expect() を使用します。例:
pm.test("Person is Jane", () => {
//assigning the response body to a constant.
const responseJson = pm.response.json();
//assert that the third person object in the response has name and age properties with a given value.
pm.expect(responseJson.person[3].name).to.eql("Jane");
pm.expect(responseJson.person[3].age).to.eql(23);
// assert that the second person object in the response as the name properties of the variable "personName"
pm.expect(responseJson.person[3].name).to.eql(pm.variables.get("personName"));
// validate the length of an array
pm.expect(responseJson.person).to.have.lengthOf(15);
});変数の作成
JSON レスポンスに基づいて変数を作成するには、pm.environment.set() を使用します。例:
var jsonData = JSON.parse(responseBody);
//assign the third person's object id to a variable named userID
pm.environment.set("userID", jsonData.person[3].id);コンソールログの実行
コンソールログはデバッグに役立ちます。以下のログステートメントがサポートされます。
- console.log()
- console.info()
- console.warn()
- console.error()
コンソールログステートメントの出力は、APIテストエディター、クラウド実行のAPIテスト出力ページ、CLIによるローカル実行の出力で確認できます。
詳細情報
Postman のメソッドの詳細については、Postman の公式ドキュメントを参照してください。