mablでは、1つ以上のAPIスニペットを組み合わせてAPIテストのカスタムスクリプトを作成できます。アサーションや変数を作成する際には、できるだけmablのローコード機能を使用することをお勧めします。カスタムスニペットの使用を複雑なシナリオに限定することで、ワークスペースのすべてのメンバーがテスト結果を容易に表示し、保守できるようになります。
この記事では、APIスニペット内でいくつかの一般的なタスクを実行する方法について説明します。
次に示す例の多くは、Postman JavaScriptオブジェクトを利用しています。このオブジェクトは、mablとPostmanとのインテグレーションにより使用できます。
XMLペイロードの使用
XMLペイロードを含むSOAP APIのスクリプトを作成する方法については、こちらをクリックしてください。
変数へのアクセス
テストの既存の変数を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}`);
レスポンスの検証
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のスクリプトリファレンスを参照してください。