<#1141 Doesn't work with native Fetch API - The fo...
# pact-js-development
g
#1141 Doesn't work with native Fetch API - The following request was expected but not received Issue created by andrzej-hanusek-tg Software versions • OS: _e.g. Mac OSX 14.1.2 (23B92) • Consumer Pact library: @pact-foundation/pact 12.1.1 • Node Version: `v16.19.1 Issue Checklist Please confirm the following: ☑︎ I have upgraded to the latest ☑︎ I have the read the FAQs in the Readme ☑︎ I have triple checked, that there are no unhandled promises in my code and have read the section on intermittent test failures ☑︎ I have set my log level to debug and attached a log file showing the complete request/response cycle ☑︎ For bonus points and virtual high fives, I have created a reproduceable git repository (see below) to illustrate the problem Expected behaviour pact-js should correctly works with Fetch API, not only with axios. BTW I don't know why in every example you are using axios. Right now, this is not a standard in web development. Actual behaviour Check below example. getMeDogsFetch method is the same like Axios implementation, but right now I'm always getting this error:
Copy code
Mock server failed with the following mismatches:

        0) The following request was expected but not received: 
            Method: GET
Steps to reproduce
Copy code
import path from 'path';
import { MatchersV3, PactV3 } from '@pact-foundation/pact';
import axios from 'axios';
import { describe, expect, it } from 'vitest';

// Create a 'pact' between the two applications in the integration we are testing
const provider = new PactV3({
  dir: path.resolve(process.cwd(), 'pacts'),
  consumer: 'MyConsumer',
  provider: 'MyProvider',
});

class DogService {
  constructor(private url: string) {}

  public getMeDogs = (from: string) => {
    return axios.request({
      baseURL: this.url,
      params: { from },
      headers: { Accept: 'application/json' },
      method: 'GET',
      url: '/dogs',
    });
  };

  public getMeDogsFetch = async (from: string, url: string) => {
    const res = await fetch(`${url}/dogs?from=${from}`, {
      headers: { Accept: 'application/json' },
      method: 'GET',
    });

    return res.json();
  };
}
// API Client that will fetch dogs from the Dog API
// This is the target of our Pact test

const dogExample = { dog: 1 };
const EXPECTED_BODY = MatchersV3.eachLike(dogExample);

describe('GET /dogs', () => {
  it('[AXIOS] returns an HTTP 200 and a list of dogs', () => {
    // Arrange: Setup our expected interactions
    //
    // We use Pact to mock out the backend API
    provider
      .given('I have a list of dogs')
      .uponReceiving('a request for all dogs with the builder pattern')
      .withRequest({
        method: 'GET',
        path: '/dogs',
        query: { from: 'today' },
        headers: { Accept: 'application/json' },
      })
      .willRespondWith({
        status: 200,
        headers: { 'Content-Type': 'application/json' },
        body: EXPECTED_BODY,
      });

    return provider.executeTest(async (mockserver) => {
      // Act: test our API client behaves correctly
      //
      // Note we configure the DogService API client dynamically to
      // point to the mock service Pact created for us, instead of
      // the real one
      const dogService = new DogService(mockserver.url);
      const response = await dogService.getMeDogs('today');

      // Assert: check the result
      expect(response.data[0]).to.deep.eq(dogExample);
    });
  });
  it('[FETCH] returns an HTTP 200 and a list of dogs', () => {
    // Arrange: Setup our expected interactions
    //
    // We use Pact to mock out the backend API
    provider
      .given('I have a list of dogs')
      .uponReceiving('a request for all dogs with the builder pattern')
      .withRequest({
        method: 'GET',
        path: '/dogs',
        query: { from: 'today' },
        headers: { Accept: 'application/json' },
      })
      .willRespondWith({
        status: 200,
        headers: { 'Content-Type': 'application/json' },
        body: EXPECTED_BODY,
      });

    return provider.executeTest(async (mockserver) => {
      // Act: test our API client behaves correctly
      //
      // Note we configure the DogService API client dynamically to
      // point to the mock service Pact created for us, instead of
      // the real one
      const dogService = new DogService(mockserver.url);
      const response = await dogService.getMeDogsFetch('today');

      // Assert: check the result
      expect(response.data[0]).to.deep.eq(dogExample);
    });
  });
});
Relevant log files
Copy code
[07:57:48.672] ERROR (74492): pact@12.1.1: Test failed for the following reasons:

  Mock server failed with the following mismatches:

        0) The following request was expected but not received: 
            Method: GET
            
FetchError: invalid json response body at  reason: Unexpected end of JSON input
pact-foundation/pact-js