nock 1.0.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 75

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.0.0

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")
      ..replay(
        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")
  ..replay(200);

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

final tagsInterceptor = nock.get(RegExp(r"^/tags$"))
  ..replay(200);

Specifying request headers #

final interceptor = nock.get("/users")
  ..headers({
    'Session-Token': '59aff48f-369e-4781-a142-b52666cf141f',
  })
  ..replay(200);

Specifying request query string #

Using query string:

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

Using example:

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

Using matchers:

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

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

Using custom match function:

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

// or

final interceptor = nock.get("/users")
  ..query((Map<String, String> params) => true)
  ..replay(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",
    },
)
  ..replay(204);

Using matchers:

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

Using custom match function:

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

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

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

Specifying reply #

application/json:

final interceptor = nock.get("/users")
  ..replay(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")
  ..replay(200, "pong");

Other binary data:

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

Specifying reply headers #

Other binary data:

final interceptor = nock.get("/auth")
  ..replay(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()
  ..replay(
    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()
  ..replay(
    200,
    "result",
  )
  ..onReply(() => print("I'm done"));

Contributions Welcome! #

Feel free to open PR or an issue

Changelog #

1.0.1 #

Add onReply() and cancel() interceptor methods

1.0.0 #

First version implemented

example/main.dart

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")
      ..replay(
        200,
        "result",
      );

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

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

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  nock: ^1.0.1

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:nock/nock.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
52
Health:
Code health derived from static analysis. [more]
99
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
75
Learn more about scoring.

We analyzed this package on Jan 19, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.0
  • pana: 0.13.4

Health issues and suggestions

Document public APIs. (-1 points)

57 out of 57 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
collection ^1.14.0 1.14.12
http ^0.12.0 0.12.0+4
test ^1.6.0 1.11.1
Transitive dependencies
_fe_analyzer_shared 1.0.3
analyzer 0.39.4
args 1.5.2
async 2.4.0
boolean_selector 1.0.5
charcode 1.1.2
convert 2.1.1
coverage 0.13.3+3
crypto 2.1.4
csslib 0.16.1
glob 1.2.0
html 0.14.0+3
http_multi_server 2.1.0
http_parser 3.1.3
io 0.3.3
js 0.6.1+1
logging 0.11.4
matcher 0.12.6
meta 1.1.8
mime 0.9.6+3
multi_server_socket 1.0.2
node_interop 1.0.3
node_io 1.0.1+2
node_preamble 1.4.8
package_config 1.1.0
package_resolver 1.0.10
path 1.6.4
pool 1.4.0
pub_semver 1.4.2
shelf 0.7.5
shelf_packages_handler 1.0.4
shelf_static 0.2.8
shelf_web_socket 0.2.3
source_map_stack_trace 1.1.5
source_maps 0.10.8
source_span 1.6.0
stack_trace 1.9.3
stream_channel 2.0.0
string_scanner 1.0.5
term_glyph 1.1.0
test_api 0.2.13
test_core 0.2.18
typed_data 1.1.6
vm_service 2.3.1
watcher 0.9.7+13
web_socket_channel 1.1.0
yaml 2.2.0
Dev dependencies
pedantic any 1.9.0