LoginSignup
2
0

テストスクリプトの例

Last updated at Posted at 2023-12-28

Home / Write scripts / Scripting reference

Test script examples

次のテスト スクリプトの例を使用して、リクエスト、フォルダー、コレクション用の独自のテスト スクリプトを作成できます。テスト スクリプトは、Postman がリクエストの送信先 API からのレスポンスを受信したときに実行されます。フォルダーまたはコレクションにテストを追加すると、その中の各リクエストの後にテストが実行されます。

テストを開始する

最初のテスト スクリプトを作成するには、Postman でリクエストを開き、[テスト]タブを選択します。次の JavaScript コードを入力します。

pm.test("Status code is 200", function () {
  pm.response.to.have.status(200);
});

このコードは、pmライブラリを使用してテストメソッドを実行します。テキスト文字列がテスト出力に表示されます。テスト内の関数はアサーションを表します。Postman テストでは、 Chai アサーション ライブラリ BDD構文を使用できます。これにより、ユーザーや共同作業者にとってテストがどの程度読みやすくなるかを最適化するオプションが提供されます。この場合、コードは BDD チェーンを使用してto.haveアサーションを表現します。

このテストでは、API から返された応答コードをチェックします。応答コードが の場合200、テストは合格します。それ以外の場合、テストは失敗します。[送信]を選択し、応答領域の[テスト結果]タブに移動します。

image.png

テスト結果が合格または不合格の場合にどのような結果になるかを確認するには、アサーション コードのステータス コードを変更して、リクエストを再度送信します。

結果の出力方法に応じて、テスト アサーションをさまざまな方法で構造化できます。次のコードは、expect構文を使用して上記と同じテストを実現する別の方法です

pm.test("Status code is 200", () => {
  pm.expect(pm.response.code).to.eql(200);
});

アサーション構文オプションの完全な概要については、Chai アサーション ライブラリのドキュメントを参照してください。

複数のアサーションを使用する

テストには、単一のテストの一部として複数のアサーションを含めることができます。これを使用して、関連するアサーションをグループ化します。

pm.test("The response has all properties", () => {
    //parse the response JSON and test three properties
    const responseJson = pm.response.json();
    pm.expect(responseJson.type).to.eql('vip');
    pm.expect(responseJson.name).to.be.a('string');
    pm.expect(responseJson.id).to.have.lengthOf(1);
});

含まれているアサーションのいずれかが失敗すると、テスト全体が失敗します。テストに合格するには、すべてのアサーションが成功する必要があります。

response body を解析する

応答に対してアサーションを実行するには、まずデータをアサーションで使用できる JavaScript オブジェクトに解析する必要があります。

JSON データを解析するには、次の構文を使用します。

const responseJson = pm.response.json();

XML を解析するには、次を使用します。

const responseJson = xml2Json(pm.response.text());

複雑な XML 応答を処理している場合は、コンソールのログ記録が役立つ場合があります。

CSV を解析するには、CSV 解析 (csv-parse/lib/sync)ユーティリティを使用します。

const parse = require('csv-parse/lib/sync');
const responseJson = parse(pm.response.text());

HTML を解析するには、cheerioを使用します。

const $ = cheerio.load(pm.response.text());
//output the html for testing
console.log($.html());

解析しない応答を処理する

応答本文が JSON、XML、HTML、CSV、またはその他の解析可能なデータ形式としてフォーマットされていないために JavaScript に解析できない場合でも、データに対してアサーションを行うことができます。

応答本文に文字列が含まれているかどうかをテストします。

pm.test("Body contains string",() => {
  pm.expect(pm.response.text()).to.include("customer_id");
});

応答本文全体に対してテストが実行されるため、文字列がどこで検出されたかはわかりません。応答が文字列と一致するかどうかをテストします。

pm.test("Body is string", function () {
  pm.response.to.have.body("whole-body-text");
});

HTTP 応答に対してアサーションを行う

テストでは、本文、ステータスコード、ヘッダー、Cookie、応答時間などを含む、リクエスト応答のさまざまな側面をチェックできます。

テスト応答本文

応答本文内の特定の値を確認します。

/* Response has the following structure:
{
  "name": "Jane",
  "age": 23
},
*/
pm.test("Person is Jane", () => {
  const responseJson = pm.response.json();
  pm.expect(responseJson.name).to.eql("Jane");
  pm.expect(responseJson.age).to.eql(23);
});

テストステータスコード

応答ステータス コードをテストします。

pm.test("Status code is 201", () => {
  pm.response.to.have.status(201);
});

ステータス コードがセットの 1 つであるかどうかをテストしたい場合は、それらをすべて配列に含めてoneOfを使用します。

pm.test("Successful POST request", () => {
  pm.expect(pm.response.code).to.be.oneOf([201,202]);
});

ステータス コードのテキストを確認します。

pm.test("Status code name has string", () => {
  pm.response.to.have.status("Created");
});

テストヘッダー

応答ヘッダーが存在することを確認します。

pm.test("Content-Type header is present", () => {
  pm.response.to.have.header("Content-Type");
});

特定の値を持つ応答ヘッダーをテストします。

pm.test("Content-Type header is application/json", () => {
  pm.expect(pm.response.headers.get('Content-Type')).to.include('application/json');
});

テストクッキー

応答に Cookie が存在するかどうかをテストします。

pm.test("Cookie isLoggedIn is present", () => {
  pm.expect(pm.cookies.has('isLoggedIn')).to.be.true;
});

特定の Cookie 値をテストします。

pm.test("Cookie isLoggedIn has value 1", () => {
  pm.expect(pm.cookies.get('isLoggedIn')).to.eql('1');
});

テストの応答時間

応答時間が指定された範囲内であるかどうかをテストします。

pm.test("Response time is less than 200ms", () => {
  pm.expect(pm.response.responseTime).to.be.below(200);
});

一般的なアサーションの例

一般的なアサーションの例

以下の一般的なアサーションの例は、テスト スクリプトの作成に役立つ可能性があります。

アサーションに含めることができる内容のより包括的な概要については、Chai Assertion Library Docsを参照してください。

変数に対する応答値をアサートする

応答プロパティが変数と同じ値を持つかどうかを確認します (この例では環境変数を使用しています)。

pm.test("Response property matches environment variable", function () {
  pm.expect(pm.response.json().name).to.eql(pm.environment.get("name"));
});

テスト スクリプトでの変数の使用の詳細については、「変数の使用」を参照してください。

値の型をアサートする

応答の任意の部分の型をテストします。

/* Response has the following structure:
{
  "name": "Jane",
  "age": 29,
  "hobbies": [
    "skating",
    "painting"
  ],
  "email": null
},
*/
const jsonData = pm.response.json();
pm.test("Test data type of the response", () => {
  pm.expect(jsonData).to.be.an("object");
  pm.expect(jsonData.name).to.be.a("string");
  pm.expect(jsonData.age).to.be.a("number");
  pm.expect(jsonData.hobbies).to.be.an("array");
  pm.expect(jsonData.website).to.be.undefined;
  pm.expect(jsonData.email).to.be.null;
});

配列プロパティのアサート

配列が空かどうか、また特定の項目が含まれているかどうかを確認します。

/* Response has the following structure:
{
  "errors": [],
  "areas": [ "goods", "services" ],
  "settings": [
    {
      "type": "notification",
      "detail": [ "email", "sms" ]
    },
    {
      "type": "visual",
      "detail": [ "light", "large" ]
    }
  ]
},
*/

const jsonData = pm.response.json();
pm.test("Test array properties", () => {
    //errors array is empty
  pm.expect(jsonData.errors).to.be.empty;
    //areas array includes "goods"
  pm.expect(jsonData.areas).to.include("goods");
    //get the notification settings object
  const notificationSettings = jsonData.settings.find
      (m => m.type === "notification");
  pm.expect(notificationSettings)
    .to.be.an("object", "Could not find the setting");
    //detail array must include "sms"
  pm.expect(notificationSettings.detail).to.include("sms");
    //detail array must include all listed
  pm.expect(notificationSettings.detail)
    .to.have.members(["email", "sms"]);
});

順番は.membersテストには影響しません。

オブジェクトのプロパティをアサートする

オブジェクトにキーまたはプロパティが含まれていることをアサートします。

/* Response has the following structure:
{
  "a": 1,
  "b": 2
},
*/
pm.expect({a: 1, b: 2}).to.have.all.keys('a', 'b');
pm.expect({a: 1, b: 2}).to.have.any.keys('a', 'b');
pm.expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd');
pm.expect({a: 1}).to.have.property('a');
pm.expect({a: 1, b: 2}).to.be.a('object')
  .that.has.all.keys('a', 'b');

ターゲットにはobject、set、 、arrayまたはを指定できますmap。または.keysを使用せずに を実行すると、式はデフォルトで になります。ターゲットによって動作が異なるため、 を使用する前に確認することをお勧めします。.all.any.all.keystypetype.keys.a

値がセット内にあることをアサートします

有効なオプションのリストに対して応答値を確認します。

/* Response has the following structure:
{
  "type": "Subscriber"
},
*/

pm.test("Value is in valid list", () => {
  pm.expect(pm.response.json().type)
    .to.be.oneOf(["Subscriber", "Customer", "User"]);
});

オブジェクトが含まれていることをアサートします

オブジェクトが親オブジェクトの一部であることを確認します。

/* Response has the following structure:
{
  "id": "d8893057-3e91-4cdd-a36f-a0af460b6373",
  "created": true,
  "errors": []
},
*/

pm.test("Object is contained", () => {
  const expectedObject = {
    "created": true,
    "errors": []
  };
  pm.expect(pm.response.json()).to.deep.include(expectedObject);
});

.deepを使用すると、チェーン内で後続するすべての.equal、.include、.members、.keys、およびアサーションで、厳密な ( ) 等価ではなく、深い等価性 (緩やかな等価性) が使用されます。また、緩やかに比較しますが、チェーン内で後続する他のアサーションにも詳細な等価比較が使用されますが、そうではありません。.property===.eql.deep.equal.eql

現在の環境をアサートします

Postman でアクティブな環境を確認します。

pm.test("Check the active environment", () => {
  pm.expect(pm.environment.name).to.eql("Production");
});

一般的なテスト エラーのトラブルシューティング

テスト スクリプトでエラーや予期しない動作が発生した場合、Postman コンソールはソースを特定するのに役立ちます。console.log()、console.info()、console.warn()、およびdebug ステートメントをテスト アサーションと組み合わせることでconsole.error()、HTTP リクエストと応答の内容、および変数などの Postman データ項目を調べることができます。console.clear()このメソッドを使用して、コンソールから情報をクリアすることもできます。コンソールアイコン Postman フッターから[コンソール]を選択して 開きます。

image.png

変数または応答プロパティの値をログに記録します。

console.log(pm.collectionVariables.get("name"));
console.log(pm.response.json().name);

変数または応答プロパティのタイプをログに記録します。

console.log(typeof pm.response.json().id);

コンソール ログを使用して、「トレース ステートメント」とも呼ばれるコードの実行をマークします。

if (pm.response.json().id) {
  console.log("id was found!");
  // do something
} else {
  console.log("no id ...");
  //do something else
}

アサーションの深い等価性エラー

エラーが発生する可能性がありますAssertionError: expected to deeply equal ''。たとえば、これは次のコードで発生します。

pm.expect(1).to.eql("1");

これは、テストが数値と文字列値を比較しているために発生します。テストは、型と値の両方が等しい場合にのみ true を返します。

変数が定義されていないエラー

エラーが発生する可能性がありますReferenceError: is not defined。これは通常、宣言されていない変数、またはテスト コードの範囲外にある変数を参照しようとしたときに発生します。

次の例では、JSON オブジェクトが最初のテストの変数の値です。2 番目のテストは変数を参照しようとしていますが、変数が 2 番目のテストのコードの範囲外にあるため参照できません。

/* Response has the following structure:
{
  "name": "John",
  "age": 29
},
*/
pm.test("Test 1", () => {
  const jsonData = pm.response.json();
  pm.expect(jsonData.name).to.eql("John");
});

pm.test("Test 2", () => {
  pm.expect(jsonData.age).to.eql(29); // ReferenceError: jsonData is not defined
});

テスト関数がグローバル スコープを参照する必要がある場合は、変数がグローバル スコープで使用できることを確認してください。前の例では、const jsonData = pm.response.json();最初のテスト関数の前に移動するとpm.test、両方のテスト関数で使用できるようになります。

アサーション未定義エラー

エラーが発生する可能性がありますAssertionError: expected undefined to deeply equal 。通常、これは存在しないプロパティ、またはスコープ外のプロパティを参照しているときに発生します。

const jsonData = pm.response.json();
pm.expect(jsonData.name).to.eql("John");

この例でエラーが発生した場合AssertionError: expected undefined to deeply equal 'John'、これはnameプロパティがオブジェクトで定義されていないことを示しますjsonData。

テストは失敗しない

テストが失敗すると予想していても、実際には失敗しない場合があります。テスト コードが構文的に正しいことを確認してから、リクエストを再送信してください。

true次の例では、 がに等しくないため、テストは失敗すると予想されますfalse。関数が適切に定義されていないため、テストは実際には合格しますpm.test。このpm.test関数には、テスト結果出力に表示されるテキスト文字列である最初のパラメータがありません。関数を使用したテストの定義pm.testについて詳しく学ぶことができます。

pm.test( function () {
    pm.expect(true).to.eql(false);
});

応答構造を検証する

Tiny Validator V4 (tv4)を使用して JSON スキーマを検証できます。

const schema = {
 "items": {
 "type": "boolean"
 }
};

const data1 = [true, false];
const data2 = [true, 123];

pm.test('Schema is valid', function() {
  pm.expect(tv4.validate(data1, schema)).to.be.true;
  pm.expect(tv4.validate(data2, schema)).to.be.true;
});

Ajv JSON スキーマ検証ツールを使用して JSON スキーマを検証することもできます。

const schema = {
  "properties": {
    "alpha": {
      "type": "boolean"
    }
  }
};

pm.test('Schema is valid', function() {
  pm.response.to.have.jsonSchema(schema);
});

非同期リクエストを送信する

テスト コードからリクエストを送信し、応答をログに記録できます。

pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    console.log(response.json());
});

Postman テストの以前の記述スタイル (非推奨)

このセクションでは、Postman の以前のバージョンで使用されていた非推奨のスクリプト構文について説明します。新しいスクリプトを作成する場合は、現在の構文を使用してください。

Postman テストの以前の記述スタイルは、testsオブジェクトの値の設定に依存していました。オブジェクト内の要素に説明的なキーを設定し、それが true か false かをアサートします。たとえば、次の例では、応答本文にuser_id文字列が含まれているかどうかがチェックされます。

tests["Body contains user_id"] = responsebody.has("user_id");

テストする項目の数に応じて、必要な数のキーを追加します。[テスト]タブの応答ビューアでテスト結果を表示します。タブのヘッダーには、合格したテストの数が表示され、tests 変数に設定したキーがリストされます。値が true と評価された場合、テストは合格です。

//Set an environment variable
postman.setEnvironmentVariable("key", "value");

//Set a nested object as an environment variable
const array = [1, 2, 3, 4];
postman.setEnvironmentVariable("array", JSON.stringify(array, null, 2));
const obj = { a: [1, 2, 3, 4], b: { c: 'val' } };
postman.setEnvironmentVariable("obj", JSON.stringify(obj));

//Get an environment variable
postman.getEnvironmentVariable("key");

//Get an environment variable whose value is a stringified object
//(Wrap in a try-catch block if the data is coming from an unknown source)
const array = JSON.parse(postman.getEnvironmentVariable("array"));
const obj = JSON.parse(postman.getEnvironmentVariable("obj"));

//Clear an environment variable
postman.clearEnvironmentVariable("key");

//Set a global variable
postman.setGlobalVariable("key", "value");

//Get a global variable
postman.getGlobalVariable("key");

//Clear a global variable
postman.clearGlobalVariable("key");

//Check if response body contains a string
tests["Body matches string"] = responseBody.has("string_you_want_to_search");

//Check if response body is equal to a string
tests["Body is correct"] = responseBody === "response_body_string";

//Check for a JSON value
const data = JSON.parse(responseBody);
tests["Your test name"] = data.value === 100;

//Content-Type is present (Case-insensitive checking)
tests["Content-Type is present"] = postman.getResponseHeader("Content-Type");
tests["Content-Type is present"] = postman.getResponseHeader("Content-Type");
//getResponseHeader() method returns the header value, if it exists

//Content-Type is present (Case-sensitive)
tests["Content-Type is present"] = responseHeaders.hasOwnProperty("Content-Type");

//Response time is less than 200ms
tests["Response time is less than 200ms"] = responseTime < 200;

//Response time is within a specific range
//(lower bound inclusive, upper bound exclusive)
tests["Response time is acceptable"] = _.inRange(responseTime, 100, 1001);

//Status code is 200
tests["Status code is 200"] = responseCode.code === 200;

//Code name contains a string
tests["Status code name has string"] = responseCode.name.has("Created");

//Successful POST request status code
tests["Successful POST request"] = responseCode.code === 201 || responseCode.code === 202;

次のステップ

さまざまなシナリオのテスト スクリプトの例を見てきましたが、独自のテストを拡張することに興味があるかもしれません。

  • テスト スクリプトで動的変数を使用する方法については、「動的変数」を参照してください。
  • オブジェクトの使用方法の詳細についてはpm、「Postman JavaScript リファレンス」を参照してください。
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0