Encountering "Missing requests" error while executing npm run pactTest on PACT.io

Check out the Test Repo I created: https://github.com/leongaban/pact-io-js-test

https://i.sstatic.net/JESkK.jpg

Anticipated Outcome

To generate a Pact file for my TotalPayout.test.pact.ts script, run npm run pactTest.

Findings

D, [#38238] DEBUG -- : {
  "description": "a GET request with a user id",
  "request": {
    "method": "GET",
    "path": "/frontoffice/api/liquidity-pool/get-total-payout",
    "headers": {
      "Accept": "application/json"
    }
  },
  "response": {
    "status": 200,
    "headers": {
      "Content-Type": "application/json"
    }
  }
}
W, [#38238]  WARN -- : Verifying - actual interactions do not match expected interactions. 
Missing requests:
  GET /frontoffice/api/liquidity-pool/get-total-payout


W, [#38238]  WARN -- : Missing requests:
  GET /frontoffice/api/liquidity-pool/get-total-payout

Behold, My Pact File

// @ts-ignore
import path from 'path';
// @ts-ignore
import { Pact } from '@pact-foundation/pact';
import { getTotalPayout } from './LiquidityPool';

// const port = 12345;
const endpoint = '/frontoffice/api/liquidity-pool/get-total-payout';

const EXPECTED_BODY = {
  total_payout: 100.21,
};

const userId = 'foo';

describe('The API', () => {
  // Copy this block once per interaction under test
  describe('getUsersTotalPayout', () => {
    beforeEach(() => {
      const interaction = {
        uponReceiving: 'a GET request with a user id',
        withRequest: {
          method: 'GET',
          path: endpoint,
          headers: {
            Accept: 'application/json',
          },
        },
        willRespondWith: {
          status: 200,
          headers: {
            'Content-Type': 'application/json'
          },
          data: EXPECTED_BODY
        },
      };

      // @ts-ignore
      return provider.addInteraction(interaction);
    });
​
    // add expectations
    it('Should call getUsersTotalPayout and return an object with the total_payout', done => {
      getTotalPayout(userId)
        .then((response: any) => {
          console.log('response', response);
          console.log('EXPECTED_BODY', EXPECTED_BODY);
          expect(response).toEqual(EXPECTED_BODY);
        })
        .then(done);
    });
  });
});

Contained in this service file is the getTotalPayout function:

This specific endpoint has not been created yet, but this Pact test is expected to function correctly.

// @TODO Note, this is the placeholder for LiquidityPool API endpoints
// @ts-ignore
import axios, * as others from 'axios';

const endpoint = '/frontoffice/api/liquidity-pool/';

export const getTotalPayout = async (userId: string) => {
  const response = await axios.get(`${endpoint}get-total-payout`, { params: userId });
  return response.data;
};

Additionally, here's my axios mock located in src/__mocks__/axios.ts

// tslint:disable-next-line:no-empty
const mockNoop = () => new Promise(() => {});

export default {
  get: jest.fn(() => Promise.resolve({ data: { total_payout: 100.21 }})),
  default: mockNoop,
  post: mockNoop,
  put: mockNoop,
  delete: mockNoop,
  patch: mockNoop
};

Answer №1

Simply put, the issue lies in your test not accessing the path

/frontoffice/api/liquidity-pool/get-total-payout
on the Pact Mock Server.

You have configured Pact to run on http://localhost:1234, so you need to ensure that your code is set up to communicate with this server instead of the actual one.

Within your axios configuration, you are essentially bypassing the http request library, leading to failed Pact tests as it anticipates a call which never occurs due to the mocking. To rectify this issue, consider the following changes:

  1. Install axios to replace the mocked out library used for http requests.
  2. Avoid mocking axios during Pact testing to allow real calls to be made and validated by Pact.
  3. Configure axios in the tests to interact with the Pact mock service using the example setup below:

pactSetup.ts:

// Configure axios to utilize the Pact mock server for testing purposes
import axios from "axios";
axios.defaults.baseURL = "http://localhost:1234";
  1. Refer to the log files generated by Pact for insights into the issues encountered. Ensure that your code accesses
    /frontoffice/api/liquidity-pool/get-total-payout
    as expected to pass the tests.

Additionally, once the previous steps have been addressed, consider utilizing Pact as a local stub server for development purposes. The necessary documentation can be found at https://github.com/pact-foundation/pact-ruby-standalone/releases.

As a recommendation, include a script in your package.json to create a local stub server for the provider, allowing you to simulate the request/responses outlined in your tests:

"stubs": "$(find . -name pact-stub-service | head -n 1) pacts/* --port 4000"

By executing npm run stubs, you can initiate a local stub on port 4000 containing the interactions specified in your tests.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for sharing JSON data between JavaScript files

Here is the initial script setup to utilize static .json files for displaying and animating specific content. The code provided is as follows: var self = this; $.getJSON('data/post_'+ index +'.json', function(d){ self.postCa ...

Playing sound files on Angular using Howler.JS

I am currently trying to incorporate the ability to play an mp3 file within a Cordova + Ionic hybrid app. The sound file is located at: www/sounds/dubstep/sound.mp3 I am attempting to play the file from a service placed in /www/scripts/services/global.j ...

Issue with Bootstrap Carousel function in desktop browsers but functioning correctly on mobile devices

I'm experiencing issues with my bootstrap carousel on mobile browsers, but not on web browsers, despite trying various fixes and clearing my browser cache. Specifically, there is no sliding effect when clicking on the indicator, and everything else ap ...

How to delete the last element of an array in Vue.js

Currently, I'm facing an issue with a filter duplication feature in my code. When I click on the "add filter" button, a duplicated filter is added to the array. However, the problem arises when I try to remove a filter using the cross icon - it always ...

Are you ready to create a Modal Factory?

For a while now, I have been utilizing modals in various front-end frameworks to communicate with users in my applications. Typically, the process involves defining the modal's html and then rendering it through a click event. As my apps continue to ...

Is there a way for me to create a route similar to Instagram's setup, such as localhost:3000

I am looking to structure my routes similar to Instagram (instagram.com/username). Currently, I have implemented the following route: router.get('/:name', loggedin, function (req, res, next) { res.render('profile', {"Request name" ...

Problem with Input Box Validation

My text input field in a web form has a JavaScript function declared like this: <asp:TextBox ID="TextBox1" runat="server" onKeyUp="javascript:Count(this);" TextMode="Number"></asp:TextBox> function Count(text) { // Handling textarea ...

Confirm that the form is valid when a specific requirement is fulfilled

I am currently working on a credit card project that involves using a JavaScript function called validateCreditCard to validate credit cards and determine the type. The idea is to store the credit card type as the value of a hidden input field called cardT ...

Tips for preventing nested subscriptions from exceeding two levels

I have four subscriptions that depend on each other. While there are numerous suggestions on avoiding nested subscriptions, they often don't address more than two levels of nesting. How can I prevent so many nested subscriptions? This is the code fo ...

The makeSVG function from GoJS is failing to generate the correct HTML SVG object

I have been utilizing the Diagram.makeSVG() method to create an SVG from my diagram. Subsequently, I appended the SVG to a new empty tab using this script (diagram represents my Diagram Object): function print() { var newTab = window.open(), svg ...

What is the reason that prototypes are not passed down through inheritance?

Can anyone shed light on why Validator.js is structured the way it is initialized (as shown in the first code snippet) and the reason behind the inability to call the validate method (as demonstrated in the second snippet)? I am currently experimenting wi ...

Utilizing Binding Time in Angular for Enhanced Views

I am completely new to Angular JS. I have a simple question that I have been searching for answers on SO. My goal is to display the current time in real-time (refreshing every second as the clock ticks) on my view. Here's what I have tried so far: H ...

Utilizing FullCalendar for showcasing comprehensive details

I'm a big fan of the fullcalendar plugin and all its amazing features. I want to enhance it by displaying more customized information for each event when in agendaWeek or agendaMonth view. Switching between views is easy, but I need help filtering out ...

Tips for shuffling the sequence of EJS variables

I am currently working on creating a quiz that consists of multiple choice questions. In order to display the Question, Correct Answer, and 3 other wrong options, I am utilizing EJS variables. The format will be similar to the following example: Question: ...

I'm a beginner when it comes to Android WebView and incorporating JavaScript into my projects

Struggling to make my Android app work with JavaScript, even though I've enabled it. Despite all the research I've done suggesting it should work, it's not. Any assistance would be greatly appreciated. Below is my Java code: protected ...

JavaScript/DOM - What sets apart a "CSS Selector" from an attribute?

When it comes to excluding declarative event handlers: <a href='#' onclick=<handler> ... /> Is there a significant difference between an Attribute and a CSS Selector? For example, if I define my own attribute: <a href='#&a ...

Transform the code to utilize AJAX jQuery

Recently, I developed a Chrome Extension that extracts data from the data-href attribute and applies it to the href attribute from a Google Search. Below is the current implementation: $(document).on("DOMSubtreeModified", function() { var e = $("#sear ...

Preventing distortion of the object when using camera.lookat() in three.js

I have created a piece of code that moves an object randomly on the screen using camera.lookat(). However, I noticed that when the object moves to the sides of the screen, it slightly changes its shape to look at the camera, causing a skewing effect. I wa ...

Looking for JavaScript code that can dynamically create an HTML table from JSON data

I am in need of a javascript solution that can dynamically generate either an HTML table or a bootstrap grid layout based on a specific data structure. [ {"x":0,"y":0,"width":2,"height":1,"title":"Lorem ipsum dolor sit amet"}, {"x":2,"y":0,"width ...

CoffeeScript and Node.js: Encountering an Unexpected ">" Token (Arrow Function)

After attempting to execute the following coffeescript, the issue arises: request = require('request') request('http://google.com', (error, response, body) -> if not error and response.statusCode is 200 console.log(body ...