Pact and Angular Trouble: The actual interactions do not align with the expected interactions for the mock MockService

Discovering the Power of Pact in Conjunction with Angular.

Encountering an unexpected error during test execution. Error: The actual interactions do not align with the expected interactions for mock MockService.

    Requests that are Missing:
            GET /dogs

Source code being tested: dog.service.ts


@Injectable({
  providedIn: 'root'
})
export class DogService {

  constructor(private http: HttpClient) {
  }

  getDogs(baseUrl: string): Observable<Dog[]>{
    return this.http.get<Dog[]>(baseUrl + '/dogs');
  }
}

Spec file:

import {TestBed} from '@angular/core/testing';
import {HttpClientModule} from '@angular/common/http';
import {PactWeb, Matchers} from '@pact-foundation/pact-web';
import { DogService } from './dog.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import {Pact} from '@pact-foundation/pact';

describe('Contract Tests for Dog Service', () => {
  let provider: PactWeb;


  let dogService: DogService;

  beforeAll(async (done) => {
        provider = new PactWeb({
            port: 1234,
            host: '127.0.0.1',
            log: '.\\log\\pact.log',
            logLevel: 'warn',
            dir: '.\\pacts',
            spec: 2
        });
          // Required for slower CI environments
        setTimeout(done, 2000);

          // Necessary if run with `singleRun: false`
        await provider.removeInteractions();

        console.log('Creating Pact web instance');
    });

  afterEach(async () => {
        await provider.verify();
        console.log('Verifying Interactions');
    });

  afterAll(async () => {
        return await provider.finalize();
        console.log('Finalizing Pact');
    });

  beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [
              DogService
            ]
          });
        console.log('Configuring Test Module');
    });

  describe('Standards Testing', () => {

      beforeAll(async () => {
        // setting up Pact interactions
        await provider.addInteraction({
          state: 'dogs exist',
          uponReceiving: 'fetch all dogs',
          withRequest: {
              method: 'GET',
              path: '/dogs'
          },
          willRespondWith: {
              status: 200,
              headers: {
                  'Content-Type': 'application/json; charset=utf-8'
              },
              body: Matchers.eachLike({
                  avatar: Matchers.like('xyz'),
                  title: Matchers.like('German Shepard'),
                  subTitle: Matchers.like('This is German Shepard'),
                  imageUrl: Matchers.like('xyz'),
                  description: 'Lorem ipsum'

              }, {min: 2}),
          },
      });
        console.log('Adding Interaction');
      });

      it('Validating Dog Details Existence', async () => {
        dogService = TestBed.inject(DogService);
        console.log(provider.mockService.baseUrl);
        dogService.getDogs(provider.mockService.baseUrl).subscribe((response) => {
            expect(response).toBeDefined();
            console.log(response);
          });

    });
    });
});

Could there be a specific issue causing this discrepancy?

Package.json: "@pact-foundation/karma-pact": "^2.3.1", "@pact-foundation/pact": "^9.11.0", "@pact-foundation/pact-node": "^10.9.4", "@pact-foundation/pact-web": "^9.11.0",

Answer №1

The error message indicates that the HTTP call was not received, which is the key clue here.

It appears that your call to getDogs is a promise but you are neither returning it nor awaiting it, leading to the possibility that the call is not being made at all.

Make sure to handle the promise properly so that the test does not complete before the call is executed.

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

Switch between showing or hiding at least three divs

I'm currently using a simple script that toggles the visibility of two div elements: <script type='text/javascript'> $(window).load(function(){ function toggle_contents() { $('#page1').toggle(); ...

Is the future of 'non-blocking' in node.js important for traditional websites?

PHP operates with a single thread, allowing it to execute one command at a time. On the other hand, node.js utilizes the 'non-blocking' feature (the event loop) which enables it to perform asynchronous functions. However, I fail to see the pract ...

Comparing scrollIntoView and moveToElement functions

When working with Selenium WebDriver, there are two primary methods to ensure an element is within the visible area: Scrolling into view: ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element); Using moveToElemen ...

Wordpress causing Jquery to malfunction; PHP function not executing

Looking to incorporate a script into my WordPress function.php file. Here's what I have so far: <?php function add_google_jquery() { if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', ...

Attempting to retrieve the key of an object nested within a JSON structure

I'm trying to extract all the key names from a JSON object, but I seem to be missing some when using the Object.keys method: var myJSON = [ { "Employees_Name": "Bill Sanders", "Work_plan_during_my_absence": "Work from home", ...

What is the process of creating Excel-like data bars using Angular?

I am seeking a way to incorporate databars behind the values in a specific column within my grid, similar to the Data Bars Conditional Formatting feature in Excel as shown here. I came across an answer that demonstrates how to achieve this using jQuery da ...

A guide on arranging array elements in an Angular application to span over multiple rows

Within my Angular application, I have a collection of companies stored in an array within my TypeScript file. These companies are dynamically rendered in the HTML using the ngFor directive as depicted in the following code snippet: <div class="card-dec ...

numerous slices of toasted bread for the latest version of Ionic

I'm looking to implement multiple toasts in Ionic framework v4, but I'm not sure how to go about coding it. I attempted to implement multiple toasts in Ionic v3, but it didn't meet my requirements. import { Component, OnInit } from '@ ...

Exploring the Powers of Typescript Interfaces within Interfaces

Can you assist me with implementing an interface wrapped within a second interface? Here is the code snippet for the reducer: import { createSlice } from '@reduxjs/toolkit'; export interface IStep { id: number; label: string; value: string ...

Utilize Moment to establish a maximum date in the datepicker settings

For the selected year in the dropdown menu, I want to determine the minimum and maximum dates for the date picker. The minimum date should be set to Jan/01/{selectedYear} and the maximum date should be Dec/01/{selectedYear}. I attempted the following code ...

Unable to access the inner object using key-value pair in Angular when working with Firebase

Within my json object, there is an inner object labeled data, containing {count: 9, message: "9 sites synced"} as its contents - also in json format. My objective is to extract the value from message, rather than count. Provided below is the temp ...

Javascript - Error encountered when utilizing a for loop to insert a new column into an array

I have been utilizing an API to fetch data on various stocks, and I am attempting to include a column named "symbol" with the query values using the function insertColumn. However, I am encountering an error message that says (node:15732) UnhandledPromiseR ...

Unable to see my Vue component within Laravel

My Vue component is not appearing on the screen and I am unable to identify the issue. I have checked my console for errors and I am using npm run hot Here is my app.js file: require('./bootstrap'); window.Vue = require('vue').default ...

Error: The provided content type 'application/x-www-form-urlencoded;charset=UTF-8' is not supported in this context

I am currently attempting to create a post using JavaScript with AJAX to communicate with a Spring controller $("#crear").click(function () { var user = document.getElementById("user").value; var client = document.g ...

Transformation of Object into Number through Function Execution in Javascript

I am currently facing an issue with my animate() function while using Three.js to generate an animation. Below is a simplified version of the code: let obj; let camera = new THREE.PerspectiveCamera(fov, asp, near, far); let scene = new THREE.Scene(); const ...

The start script failed to run when executing `npm run start`

I am new to nodejs and encountered an error when running the command npm run start. I suspect a version compatibility issue between node and npm, but it seems like that may not be the case according to the logs. 0 info it worked if it ends with ok 1 verbos ...

Adjust the color of the Icon within the tab in Material-UI

I'm attempting to change the color of the tab icon that is highlighted while keeping the others unchanged, but I am struggling to find a solution. I am using a MUI component inside the icon button. <Tab icon={ ...

JavaScript incorporates input range sliding, causing a freeze when the mouse slides rapidly

Currently working on a custom slider and encountering an issue. When quickly moving the mouse outside the slider's range horizontally, exceeding its width, the slider doesn't smoothly transition to minimum or maximum values. Instead, there seems ...

How to identify alterations in user input within Angular?

I need assistance with my search input functionality. I want to ensure that the this.searchProperties.emit is only triggered when the user interacts with the input field by touching it or making an input. The current issue is that the emit function gets ca ...

Is there a way to execute code before a user navigates away from the page?

Every attempt I've made has failed. I am trying to execute some code before the user exits the page: window.onbeforeunload = function(){ alert(1); } window.addEventListener("beforeunload", function(e){ alert(2); }); window.addEve ...