Simulated function invocation just one time

I am testing the functionality of two functions in the same file. One of the functions is supposed to call the other, and I need to verify that this interaction occurs.

import * as strings from './strings';

const generateUuidSpy = jest.spyOn(strings, 'generateUuid');

describe('getContextId()', () => {
  it('should return a string id when provided with context and a number', () => {
    const actual = strings.getContextId('testQueue', 5);
    const expected = 's1-s5';
    expect(typeof actual).toBe('string');
    expect(actual).toEqual(expected);
  });
  it('should trigger generateUuid()', () => {
    strings.getContextId('notTestQueue');
    expect(generateUuidSpy).toHaveBeenCalled();
  });
});

describe('generateUuid()', () => {
  it('should return a UUID string with 36 characters', () => {
    generateUuidSpy.mockRestore();
    const actual = strings.generateUuid();
    const expected = /[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/;
    expect(actual.length).toBe(36);
    expect(typeof actual).toBe('string');
    expect(expected.test(actual)).toBe(true);
  });
});

However, I encountered the following error:

expect(jest.fn()).toHaveBeenCalled()

    Expected mock function to have been called, but it was not called.

      12 |   it('it should execute generateUuid()', () => {
      13 |     strings.getContextId('notTestQueue');
    > 14 |     expect(generateUuidSpy).toHaveBeenCalled();
         |                             ^
      15 |   });
      16 | });
      17 |

      at Object.toHaveBeenCalled (src/helpers/strings.test.js:14:29)

Answer №1

To resolve the problem, I modified the exported functions in strings.js to export a class containing each function. In my testing process, I created a new instance of the class and utilized it for running the 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

Displaying varied information based on JSON feedback using AngularJS

I am currently in the process of developing an app using AngularJS and the Ionic framework. The app will display a list of data with various subcategories for each item, depending on the account type. View sample image here The issue I am facing is that ...

Exploring the controller logic in Sails.js index.ejs

I'm struggling to understand how to integrate dynamic logic into the homepage of my Sails.js application. Currently, the homepage is static, but I want to display data on the index.ejs page. I have a MainController with an index function that retrieve ...

What is the best way to include the "onChange" function in a component that does not natively support this prop?

After finding a useful code snippet on this page to switch languages, I attempted to enhance it by incorporating material UI components for better styling. However, whenever I change the language, it redirects me back to the home page because the MenuList ...

Having trouble converting response.data to a string in ReactJS

import React, { Component } from 'react' import TaskOneServices from '../services/TaskOneServices' import circle from '../assets/icons/dry-clean.png' import tick from '../assets/icons/check-mark.png' async function ...

Having trouble importing Tone.js in your Next.js project?

Having trouble importing Tone in my Next.js project. Despite having Tone as a dependency, I face an issue when trying to run import * as Tone from 'tone'. Next.js shows an error stating it can't locate the module node_modules/tone/build/esm/ ...

Tips for retrieving data from a database with just one key press

There is a text field that triggers a JavaScript function when a key is pressed. <input type="text" class="text" id="txt_sh_vid" onKeyPress="vhc_record()" maxlength="4"> The function takes the input from the text field and searches for a result in t ...

Eliminate unnecessary CSS classes from libraries such as bootstrap when working on a React project

Our team is currently in the process of developing a React project that involves webpack and babel. Our goal is to automatically remove any unused CSS classes from CSS frameworks Bootstrap and AdminLTE 2, which are integral parts of our project. For this ...

Encountering Karma Angular Error: Name 'X' Not Found

After executing Karma Start in my Angular project, I am encountering several errors. All the error messages highlight issues like 'Cannot find name Blob', 'Cannot Find name KeyboardEvent', 'Cannot find name HTMLElement', amon ...

React / Next.js Rendering Problem, Data Discrepancy Between Client and Server

A new feature has been added to a webpage where an image background and a city name are displayed on top of it. The data file that generates these image backgrounds and city data consists of a standard array of objects. The challenge lies in dynamically l ...

Incorporate information into a React component

I'm currently working on my initial react component and facing a challenge while adding items to the parent element through an external click event. The user needs to select from a list of search results, and I intend for these selections to be incorp ...

The route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...

Enhance your Highmap R or JavaScript visualization with a unique custom legend feature

Provided below is my code snippet, output$map <- renderHighchart({ region_map = hcmap("countries/nz/nz-all") highchart(type = "map") %>% hc_title(text = "Average") %>% hc_add_series_map(map = region_map, df = data1, joinBy = " ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

Tips for seamlessly integrating XHP and ReactJS for a component's implementation

Imagine this scenario: a blog with a posts feed. Upon loading the page, three <PostCard>s are already loaded from the server-side. As the user scrolls down or clicks a Load more button, new post cards should be dynamically added to the page. We have ...

Creating a Clickable SVG Element in React

I've been attempting to set up an onClick event in React, specifically within an SVG that includes multiple circle objects. However, when using "onClick," I'm encountering a strange issue: Upon data load, the onClick event is triggered six times ...

"Conducting API calls in NextJS: Why is Axios/Fetch returning incorrect results when using the post

I'm trying to use a post method on an API, but for some reason when I call the function it posts to the wrong path of the API. Here is the script I am using for the post: //Creating Order const createOrder = async (data) => { try { co ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

Is it possible to nest v-for directives within a component file?

Even after going through the VueJS tutorials multiple times, I am still unable to find a solution to this problem. My issue revolves around displaying a list of lists using accordions, which is supposed to work smoothly with vue-strap components. For exa ...

While making changes, I was anticipating a "for-of" loop to be used instead of a "for" loop

There seems to be an issue with TSlint and its disapproval of using the traditional for(i=0; ...) loop. Consider this straightforward code snippet: this.filters['1','2','3'....]; for (let i = 0; i < this.filters.length; i+ ...

Node.js: Troubleshooting a forEach Function Error

I am encountering an issue with my nodejs script that is causing a "function not found" error after trying to insert data from json files into Firestore. How can I resolve this? Thank you for your help. Below is my code snippet: var admin = require("f ...