パッケージ、リポジトリ、アプリカテゴリを検索

パッケージ詳細v1.2.3

nock

Dart および Flutter 向けの HTTP リクエストモックライブラリ。アプリケーションを独立してテストします。

AndroidiOSmacOSWindowsLinux
30日間ダウンロード
5.7万
いいね数
24
Pub ポイント
130

パッケージをインストール

flutter pub add nock

パッケージ概要

公開情報に基づく選定ガイドです。参考としてご利用ください。

Nock は、実際のネットワーク呼び出しを行わずにアプリケーションの隔離テストを可能にする、Dart および Flutter 用のライブラリです。開発者が期待されるリクエストパターンと応答を定義できるため、信頼性が高く再現可能なテスト環境を確保できます。ユニットテストや統合テストに最適で、アプリが正常、エラー、境界ケースなどさまざまなHTTPシナリオをどのように処理するかを検証できます。テスト中にHTTPリクエストをインターセプトすることで、テストのスピードと信頼性が向上します。このライブラリは、Android、iOS、macOS、Windows、Linux を含むすべての主要プラットフォームをサポートしています。

用途

  • API統合のテスト
  • ネットワーク障害のシミュレーション
  • リクエストペイロードの検証
  • 外部サービスからテストを分離する
  • さまざまな応答シナリオのモック化

主な機能

  • リクエストのインターセプト
  • 柔軟な応答モック
  • すべてのプラットフォームをサポート
  • 最小限のボイラープレートで簡単にセットアップ
  • テストフレームワークとの統合

適している対象

  • ユニットテストおよび統合テストを書く開発者
  • 一貫したテスト環境を必要とするチーム
  • 複雑なAPIインタラクションを備えたプロジェクト
  • テスト駆動開発ワークフロー
  • CI/CD パイプライン

注意事項

  • 本番環境での使用を想定していません
  • テストファイルでの慎重な設定が必要です
  • 新しいHTTPクライアントライブラリ用の更新が必要になる可能性があります
  • HTTPモックのみに制限
  • HTTPS証明書の検証に対応していません

元の README

関連するソースリポジトリの README 原文のスナップショットです。最新の内容はリポジトリをご覧ください。

Nock

HTTP requests mocking library for dart and flutter.

Nock can be used to test modules that perform HTTP requests in isolation.

Inspired by nock

Installing

Add dev dependency to your pubspec.yaml:

dev_dependencies:
  nock: ^1.2.3

Basic usage example:

import 'package:test/test.dart';
import 'package:http/http.dart' as http;
import 'package:nock/nock.dart';

void main() {
  setUpAll(() {
    nock.init();
  });

  setUp(() {
    nock.cleanAll();
  });

  test("example", () async {
    final interceptor = nock("http://localhost/api").get("/users")
      ..reply(
        200,
        "result",
      );

    final response = await http.get("http://localhost/api/users");

    expect(interceptor.isDone, true);
    expect(response.statusCode, 200);
    expect(response.body, "result");
  });
}
No mock found

if some request isn't mocked NetConnectionNotAllowed exception will be thrown:

void main() {
  test("example", () async {
    expect(
      http.get("http://localhost/api/users"),
      throwsA(TypeMatcher<NetConnectionNotAllowed>()),
    );
  });
}

API

Creating requests scope
final String baseUrl = "https://my-server.com";
final scope = nock(baseUrl);
Methods for creating interceptors
  • scope.get(dynamic url) -> Interceptor
  • scope.post(dynamic url, dynamic body) -> Interceptor
  • scope.put(dynamic url, dynamic body) -> Interceptor
  • scope.delete(dynamic url, dynamic body) -> Interceptor
  • scope.patch(dynamic url, dynamic body) -> Interceptor
  • scope.head(dynamic url, dynamic body) -> Interceptor
Using default base url

You could specify baseUrl for automatic scope usage:

void main(){
  setUpAll((){
    nock.defaultBase = "http://localhost/api";
    nock.init();
  });

  test("example", () async {
    nock.get("/users"); // create mock for GET http://localhost/api/users
  });
}
Url matching

You could use strings, regexp or any matcher from package:test:

final topicsInterceptor = nock.get("/topics")
  ..reply(200);

final usersInterceptor = nock.get(startsWith("/users"))
  ..reply(200);

final tagsInterceptor = nock.get(RegExp(r"^/tags$"))
  ..reply(200);
Specifying request headers
final interceptor = nock.get("/users")
  ..headers({
    'Session-Token': '59aff48f-369e-4781-a142-b52666cf141f',
  })
  ..reply(200);
Specifying request query string

Using query string:

final interceptor = nock.get("/users")
  ..query("ids[]=1&ids[]=2")
  ..reply(200);

Using example:

final interceptor = nock.get("/users")
  ..query({"id": 5})
  ..reply(200);

Using matchers:

final interceptor = nock.get("/users")
  ..query(startsWith("something"))
  ..reply(200);

final interceptor = nock.get("/users")
  ..query({'id': anyOf([1, 2, 3])})
  ..reply(200);

Using custom match function:

final interceptor = nock.get("/users")
  ..query((Map<String, List<String>> params) => true)
  ..reply(200);

// or

final interceptor = nock.get("/users")
  ..query((Map<String, String> params) => true)
  ..reply(200);
Specifying request body

Interceptor will parse HTTP request headers and try parse body.

Supported mime-types:

  • application/x-www-form-urlencoded
  • application/json
  • application/text
  • application/text

Using example:

final interceptor = nock.post(
    "/users",
    {
      "name": "John",
      "email": "john_doe@gmail.com",
    },
)
  ..reply(204);

Using matchers:

final interceptor = nock.post(
    "/users",
    {
      id: anyOf([1, 2, 3])
      name: any,
      email: TypedMather<String>(),
    },
)
  ..reply(204);

Using custom match function:

final interceptor = nock.post(
    "/users",
    (body) => body is Map,
)
  ..reply(204);

If you send binary data you could use custom raw match function:

final interceptor = nock.post(
    "/users",
    (List<int> body) => true,
)
  ..reply(204);
Specifying reply

application/json:

final interceptor = nock.get("/users")
  ..reply(200, [
    {
      "id": 1,
      "name": "John",
      "email": "john_doe@gmail.com",
    },
    {
      "id": 2,
      "name": "Mark",
      "email": "zuckerberg@gmail.com",
    },
  ]);

text/plain:

final interceptor = nock.get("/ping")
  ..reply(200, "pong");

Other binary data:

final interceptor = nock.get("/video")
  ..reply(200, <int>[73, 32, 97, 109, 32, 118, 105, 100, 101, 111]);
Specifying reply headers

Other binary data:

final interceptor = nock.get("/auth")
  ..reply(204, null, {
    "Session-Token": "59aff48f-369e-4781-a142-b52666cf141f",
  });
Persistent requests

To repeat responses for as long as nock is active, use .persist().

final users = nock.get("/users")
  ..persist()
  ..reply(
    200,
    "result",
  );

Note that while a persisted mock will always intercept the requests, it is considered "done" after the first interception.

Canceling pending mock:

users.cancel();
Do something after reply
final users = nock.get("/users")
  ..persist()
  ..reply(
    200,
    "result",
  )
  ..onReply(() => print("I'm done"));
Contributions Welcome!

Feel free to open PR or an issue

カテゴリー

依存関係

依存関係一覧 2 件

ソースリポジトリ

このパッケージを使用しているプロジェクト