Skip to content
pubscout

nock

1.2.3, released 3 years ago by an unverified publisher

HTTP requests mocking library for Dart and Flutter.

$ flutter pub add nock
Source repository

What it does

Allows you to intercept and mock HTTP requests in your Dart and Flutter applications. It enables testing of modules that perform HTTP requests in isolation by defining expected routes, request bodies, query parameters, headers, and responses.

AI-written summary of version 1.2.3, based on the package's README and metadata. Report an inaccuracy

Use it when

  • You want to unit or widget test code that makes HTTP requests without hitting real servers.
  • You need to test different HTTP response statuses, headers, bodies, and delays.

Skip it when

  • You are running integration tests against a real staging or production backend.

Strengths

  • Supports multiple HTTP methods (GET, POST, PUT, DELETE, PATCH, HEAD).
  • Allows custom matchers for URLs, query parameters, and request bodies.
  • Supports persistent mocks and response delays.

Weaknesses

  • Throws `NetConnectionNotAllowed` if a request is not explicitly mocked, which might require careful setup in complex tests.

Setup

Kind
Pure Dart
Effort
Low
Code generation
No
Direct dependencies
2

Initialize nock in `setUpAll` and clean mocks in `setUp` using `nock.init()` and `nock.cleanAll()`.

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");
  });
}

Alternatives

Packages that do the same job and could replace nock.

Works with

Packages commonly used together with nock: ones it builds on, ones built on it, and its own family.