Mocking Multiple Instances of Classes in Jest

I am currently working on a project where I have a class that creates multiple instances of the same object. I am trying to mock this behavior in jest, but I keep encountering an error specifically for the second instance creation test.

Error: expect(received).toBe(expected) // Object.is equality

Expected: "This is the-second-greeting"

Received: "This is the-first-greeting"

Expected: "Hello and Good Evening"

Received: "Hello and Good Morning"

import {Greeting} from 'somefile/greeting'

interface FooProps {
  myProps: string
}

class Foo {
  private greeting1: Greeting;
  private greeting2: Greeting;

  constructor(bar: Bar, id: string, props: FooProps) {

    this.greeting1 = new Greeting(bar, `${id}-first-greeting`, {
      prop1: 'Hello and Good Morning',
      prop2: {
        source: ['random']
      }
    })

    this.greeting2 = new Greeting(bar, `${id}-second-greeting`, {
      prop1: 'Hello and Good Evening',
      prop2: {
        source: ['anotherRandom']
      }
    })
  }
}
import Foo from 'somefile/foo'
import {Greeting} from 'somefile/greeting'
 
jest.mock('somefile/greeting');
const FirstMock = mocked(Greeting, true);
const SecondMock = mocked(Greeting, true);

const id = 'This is';

describe('Greeting', () => {
  let bar: Bar;
  let foo: Foo;
  let random1 = ['random'];
  let random2 = ['anotherRandom'];

  const props: FooProps = {
    myProps: 'myProps'
  }
  
  beforeEach( () => {
    bar = new Bar();
    foo = new Foo(bar, id, props);
  })

  afterEach( () => {
    jest.clearAllMocks();
  })

  it('should create first greeting', () => {
    expect(random.mock.calls[0][0]).toBe(bar)
    expect(random.mock.calls[0][1]).toBe(`${id}-first-greeting`)
    expect(random.mock.calls[0][2]?.prop1).toBe('Hello and Good Morning')
    expect(random.mock.calls[0][2]?.prop2.source).toBe(random1)
  })

  it('should create second greeting', () => {
    expect(random.mock.calls[1][0]).toBe(bar)
    expect(random.mock.calls[1][1]).toBe(`${id}-second-greeting`)
    expect(random.mock.calls[1][2]?.prop1).toBe('Hello and Good Evening')
    expect(random.mock.calls[1][2]?.prop2.source).toBe(random2)
  })  

})

Although the first test passes successfully, there seems to be an issue with retaining old values when running the second test. Any ideas on how to resolve this?

Answer №1

It's recommended to employ jest.resetAllMocks();

clearAllMocks entirely erases the mock state, resulting in the loss of all configured values.

Conversely, resetAllMocks restores the mock to its initial state.

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

Time when the client request was initiated

When an event occurs in the client browser, it triggers a log request to the server. My goal is to obtain the most accurate timestamp for the event. However, we've encountered issues with relying on Javascript as some browsers provide inaccurate times ...

What is the best way to turn my thumbnail into a clickable link while having the title positioned to the right?

Is there a way to create a thumbnail that acts as a link and position the title next to the thumbnail? I have experimented with using 'after' and modifying the HTML structure to align them horizontally. Any ideas on how I can achieve this layou ...

GWT's Stylish Image Carousel

Can anyone recommend a simple image slider for GWT that meets the following requirements: Slides several images from right to left when user clicks on the image (selected image should be at the center) Has endless looping capability (the last image shoul ...

Using Jquery to toggle the visibility of a DIV element and adding a blinking effect when it becomes visible

I have a hidden div that is displayed when a link is clicked, and I want it to blink as well. Here is my current setup: The link to display the hidden div: <a class="buttons" href="#" onclick="show(this)">join us</a> The hidden div to be di ...

Can you incorporate PHP variables into your JavaScript code?

Similar Question: passing variables from php to javascript I am working on dynamically generating a list where each row should have hover effects and be clickable to a specific link. The goal is to pass the ID of the content in each row through the li ...

What is the best way to retrieve JSON data values for buttons that have been clicked and files that have

Is there a way to retrieve JSON data only for clicked buttons and uploaded files? Currently, I am receiving all button values, whether clicked or not, in one instance, and file paths with fake paths like C:\\fakepath\\test.txt in anothe ...

Building an interactive table with rows that can be easily rearranged

Looking to build a table of items similar to the one found on this invoice using Ruby on Rails. Any suggestions on where to begin? I am still learning JavaScript. Is there a gem available that can help with this task? ...

Utilizing raycasting to target specific components within a glTF model and incorporate event listeners

I'm in the process of creating an interactive web application. Recently, I successfully imported a glb file into my scene. Now, I'm looking to incorporate two key functionalities: onMouseover: When hovering over one of the elements within the o ...

Is it possible to modify an input using a specific code?

Is it possible to dynamically change the value of a form input based on specific codes entered in another input without using PHP? For example, when a user enters "HFS73H" into one input, the value of another input changes to "John" - and if a different ...

What exactly does a 'hoisted manifest' mean when it comes to using Yarn?

Encountering an issue while attempting to install a package using yarn, I am receiving the error message: expected hoisted manifest for \"myPackage#@material-ui/core#react-dom\" However, the concept of a 'hoisted manifest' is not entir ...

AuthGuard in Ionic 4 causing delay in page routing permissions

In my ionic 4 app, I store user information natively. The goal is to direct users to the Home Page if their information is already stored when they open the app. If not, they should be routed to the Login Page - pretty standard procedure. However, the iss ...

What techniques can I use to generate code dynamically for transferring an object to a different Node process?

I'm in the process of developing a node server that must execute potentially unsafe code. To ensure security, I am utilizing a Sandbox API that guards against attacks and provides results and outputs from scripts. This API employs a modified global ob ...

Experimenting with animating an element through onClick event using JavaScript

I would like to create an animated div using JavaScript that activates on click. <div class="Designs"> <p>Designs</p> <div class="Thumbnails" data-animation="animated pulse"> <a href=" ...

integrating jquery with Ruby on Rails version 3

I am facing an issue in my rails application where I am trying to implement a jQuery effect. Specifically, I want a button that will hide the content within a paragraph tag when clicked. Despite trying various approaches, I have been unable to get it worki ...

Ordering tables in jQuery with both ascending and descending options

Trying to sort a table in ascending and descending order using jQuery? Here's the JavaScript code for it. However, encountering an error: Cannot read property 'localeCompare' of undefined If you can provide guidance on how to fix this so ...

The form fails to submit when the page automatically reloads

I have a PHP web application that requires certain variables on this page to be automatically refreshed. To achieve this, I have moved the processing to another page called "test.php", which is loaded into this div every 10 seconds. <script type="text ...

What is the best way to defer the instantiation of a particular controller (not a route) in your

What I'm looking for is a directive that functions like a typical ng-controller, but I need it to be invoked only after a promise has been resolved. To achieve this in HTML, it could be implemented as such: <div ng-controller="myCtrl" ctrl-promise ...

Using the useEffect hook with Redux-Toolkit dispatch causes an endless cycle of execution

Issue I am encountering an infinite loop problem when using useMutation from react-query to make post requests, retrieve user information from JSON, and then store it in my redux store using useEffect based on the status provided by the useMutation hook. ...

Modify css backgroundPosition with Jquery dynamically for both left and top offsets

As a beginner programmer and not a native English speaker, I apologize in advance for any coding or language errors. My goal is to create a 'cropping effect' by making a table draggable over an image. When the table is dragged, I want to replace ...

Do type declaration files for NPM packages have to be in the .d.ts format?

I believe it is feasible to include type declarations in any typescript file like '.d.ts', '.ts', or '.tsx'. However, I have observed that the type declaration files for most npm packages are .d.ts files. Is this a requireme ...