Taunting a specific occurrence inside a group

Good evening,

I am currently in the process of developing tests for the TypeScript class shown below. My goal is to create a test that ensures the postMessage method of the internal BroadcastChannel is called. However, I am facing difficulties in setting up the appropriate spy for this task. It seems like the issue lies in not properly attaching the spy to the actual instance within the class, but I'm uncertain about how to resolve it.

export class BroadcastChannelService<T> {
  private readonly broadcastChannel: BroadcastChannel;

  constructor(name: CHANNEL_NAMES) {
    this.broadcastChannel = new BroadcastChannel(name);
  }

  postMessage = (msg: T) => {
    this.broadcastChannel.postMessage(msg);
  }
}

Below is the current state of the test that I have developed:

import { BroadcastChannel } from 'broadcast-channel';

import { BroadcastChannelService } from '../../services';

jest.mock('broadcast-channel');
const mockedBroadcastChannel = BroadcastChannel as jest.Mocked<typeof BroadcastChannel>;

describe('BroadcastChannelService', () => {
  let subject: BroadcastChannelService<string>;

  describe('constructor', () => {
    afterAll(() => {
      jest.resetAllMocks();
    });

    test('is successful', () => {
      // eslint-disable-next-line no-unused-vars
      subject = new BroadcastChannelService<string>('GOOGLE_AUTH');
      expect(mockedBroadcastChannel).toBeCalledWith('GOOGLE_AUTH');
      expect(mockedBroadcastChannel).toBeCalledTimes(1);
    });
  });

  describe('postMessage', () => {
    beforeAll(() => {
      subject = new BroadcastChannelService('GOOGLE_AUTH');
      subject.postMessage('Hello World');
    });

    afterAll(() => {
      jest.resetAllMocks();
    });

    test('is successful', () => {
    });
  });
});

Answer №1

One clever technique involved using the spyOn method in conjunction with mockedBroadcastChannel.prototype

import { BroadcastChannel } from 'broadcast-channel';
import { BroadcastChannelService } from '../../services';

jest.mock('broadcast-channel');
const mockedBroadcastChannel = BroadcastChannel as jest.Mocked<typeof BroadcastChannel>;

describe('BroadcastChannelService', () => {
  let subject: BroadcastChannelService<string>;

  describe('constructor', () => {
    test('is successful', () => {
      // eslint-disable-next-line no-unused-vars
      subject = new BroadcastChannelService<string>('GOOGLE_AUTH');
      expect(mockedBroadcastChannel).toBeCalledWith('GOOGLE_AUTH');
      expect(mockedBroadcastChannel).toBeCalledTimes(1);
    });
  });

  describe('postMessage', () => {
    test('is successful', () => {
      const postMessageSpy = jest.spyOn(mockedBroadcastChannel.prototype, 'postMessage');
      subject = new BroadcastChannelService<string>('GOOGLE_AUTH');
      subject.postMessage('Hello World');
      expect(postMessageSpy).toBeCalledTimes(1);
      expect(postMessageSpy).toBeCalledWith('Hello World');
    });
  });
});

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

Creating a Vue Directive in the form of an ES6 class: A step-by-step

Is it possible to make a Vue directive as an ES6 Class? I have been attempting to do so, but it doesn't seem to be working correctly. Here is my code snippet: import { DirectiveOptions } from 'vue'; interface WfmCarriageDirectiveModel { ...

What is the best way to include a non-data custom attribute in a TSX template without any value?

Currently, I am working on a React component with Typescript. The initial code looks like this.... const NameFormatter = React.createClass({ render() { return ( <div> <div className="dataset-name"> ...

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

Leverage the power of JavaScript functions within the app.component.ts file of

I have a JavaScript file named action.js and I am trying to incorporate it into an Angular project. After doing some research, I found out that the js file should be placed in the assets folder and the path must be referenced in the scripts array within an ...

What is the correct way to write SVG markup within SVG tags in a React and NextJS environment?

I currently have a Svg component set up like this interface SvgIconProps { children: React.ReactNode; strokeWidth?: number; width?: number; height?: number; className?: string; } export const SvgIcon = ({ children, strokeWidth = 1, width = ...

Issue: Unable to link with 'dataSource' as it is not a recognized feature of 'mat-tree'

Upon following the example provided at https://material.angular.io/components/tree/overview, I encountered an error when trying to implement it as described. The specific error message is: Can't bind to 'dataSource' since it isn't a kn ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Developing a dynamic modal using Angular and embedding Google Maps within an iframe

I'm currently working on implementing a modal in my Angular application that, when opened, displays Google Maps within an iframe. The problem I'm facing is that the iframe isn't loading and I'm receiving this error in the browser conso ...

Displaying images in Ionic from a JSON URL source

I am having trouble getting an image from a JSON to display on an Ionic card. Although I can see the JSON response in the console log, the image is not showing up on the card, leaving it blank. It seems like I'm making a mistake in the HTML code. Any ...

Tips for retrieving items from <ng-template>:

When the loader is set to false, I am trying to access an element by ID that is located inside the <ng-template>. In the subscribe function, after the loader changes to false and my content is rendered, I attempt to access the 'gif-html' el ...

Cross-origin request error persists despite configuring headers on the server. Unable to successfully relocate image to designated directory on the server

I am encountering a CORS error specifically when sending delete requests from Angular to Laravel. Additionally, I am facing issues with moving car model images to the directory during posting, resulting in errors. I have implemented a CORS middleware and a ...

Updating the page dynamically in React/Redux by making API calls based on user submissions

My current task involves calling an API with Redux, triggering the call based on a form submission. If the query is empty, it should return all lists; otherwise, it should only return lists that match the query. // List.tsx import React, { useEffect, useS ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

What are the solutions for resolving 'undefined' errors while working with TypeScript Interfaces?

When working with TypeScript in my Next.js project, I encountered the following error message: Type '{ banner: { id: number; bannerImageUrl: string; } | undefined; }' is not assignable to type 'IntrinsicAttributes & Banner'. Prope ...

Fire the props.onChange() function when the TextField component is blurred

Currently, I am in the process of developing a NumberField component that has unique functionality. This component is designed to remove the default 0 value when clicked on (onFocus), allowing users to input a number into an empty field. Upon clicking out ...

Encountering an endless loop within a data rest API in a React application

Currently, I am in the process of learning React and attempting to utilize the Poke API with my application. Unfortunately, I seem to have run into an infinite loop issue and I am feeling quite lost in terms of troubleshooting it. Below is a snippet of my ...

Learn the process of seamlessly uploading various document formats, videos, and previewing documents with Angular software

I am having trouble viewing uploaded files in the carousel. While I can see video and image files, other document formats are not displaying. Can someone please recommend a solution to enable viewing all types of documents as well? mydata = [] onSelect ...

Error message: The types in React Redux typescript are incompatible and cannot be assigned to each other

I recently converted my React App to TypeScript and encountered an error that I'm having trouble understanding. Any help would be greatly appreciated. Here is the code for my "mapStateToProps" function: function mapStateToProps(state: AppState): MapS ...

Exploring TypeScript and node.js development using Visual Studio 2012 express

Is there a way to successfully write, build, and execute a node.js application in Visual Studio? I have already installed the TypeScript extension on VS as well as the node.js package. However, when I attempt to create a new project of the TypeScript type, ...

What is the best way to find out if multiples of a specific time interval can evenly divide the time between two

I'm currently utilizing Luxon for handling dates and durations. I have two specific dates and an ISO duration, and I am looking to figure out how to determine if the interval between the dates is a multiple of the specified duration without any remain ...