cah4a / dart_nock

HTTP requests mocking library for dart and flutter.
https://pub.dev/packages/nock
MIT License
20 stars 14 forks source link

POST requests with body aren't working #12

Closed kzietek closed 2 years ago

kzietek commented 2 years ago

Like mentioned in title, POST requests with body specified result in exception.

I'm on nock 1.2.0

Below is the reproduction code:

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("GET", () async {
    final interceptor = nock("http://localhost/api").get("/users")
      ..reply(
        200,
        "result",
      );

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

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

  test("POST without body", () async {
    final interceptor = nock("http://localhost/api").post("/users")
      ..reply(
        200,
        "result",
      );

    final response = await http.post(Uri.parse("http://localhost/api/users"));

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

  test("POST with body - DOESN'T WORK", () async {
    final interceptor = nock("http://localhost/api").post("/users")
      ..reply(
        200,
        "result",
      );

    final response = await http.post(Uri.parse("http://localhost/api/users"), body: "{}");

    expect(interceptor.isDone, true);
    expect(response.statusCode, 200);
    expect(response.body, "result");
  });
}
cah4a commented 2 years ago

Hey @kzietek!

It was intentional. You should specify the matcher for the request body, like so: nock.post("/test", {}).

Of course, you could use anything matcher, but that consider bad practice because you actually don't test what your application sends to the server.