Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text:

The Component class:

import {sayHello} from './helloworld-service';

@Component({
  tag: 'comp-home',
  styleUrl: 'comp-home.scss',
  shadow: false,
  scoped: true
})
export class MyComponent {

public callHelloWorldService () {
 return sayHello();

} }

The Service class code is as follows:

export function   sayHello  () {
 return "Hello!";
}

I needed to mock this function in my test method for proper testing, with the following setup:

jest.mock('../helloworld/helloworld-service', () => ({
  sayHello: jest.fn()
}));
import { sayHello } from '../helloworld/helloworld-service';

const mockSayHello = sayHello as jest.Mock;


describe('mycomp-tests', () => {

  let compInstance;

  beforeEach(() => {
    mockSayHello.mockClear();
    compInstance = new MyComponent();
  });
  afterEach(() => {
    jest.clearAllMocks();
  });


  it('should return mock value', () => {
   mockSayHello.mockReturnValue("yahoo");
   expect(compInstance.callHelloWorldService()).toBe("yahoo");
  });

Even after setting up the mocks, calling the service method directly in the test works fine, but when calling it through the component, the original method is invoked instead of the mocked one:

  it('should return mock value', () => {
   mockSayHello.mockReturnValue("yahoo");
   expect(compInstance.callHelloWorldService()).toBe("yahoo");//Fails ,return value is Hello !
  });

To ensure that the components also use the mocked methods during testing, additional steps may be required. This behavior is crucial for correctly simulating REST calls in tests.

Answer №1

During my stencil unit tests, I parodied functions in this manner

import * as GoodbyeService from '../goodbye/goodbye-service';

GoodbyeService.sayGoodbye = jest.fn().mockReturnValue("ciao");

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

Conceal the object, while revealing a void in its place

Is there a way to hide an image but keep the containing div blank with the same dimensions? I want it to appear as if no content was there, maintaining the original width and height. For example: http://jsfiddle.net/rJuWL/1/ After hiding, "Second!" appea ...

Using a Javascript while loop to iterate through an array and display the elements in the .innerHTML property

As a newcomer to Javascript, I am in the process of teaching myself. My current task is to develop a function that will display each element of the array AmericanCars with a space between them. I have successfully been able to show an individual element u ...

What is the process for importing a JSON5 file in Typescript, just like you would with a regular JSON file?

I am looking to import a JSON5 file into a JavaScript object similar to how one can import a JSON file using [import config from '../config.json']. When hovering over, this message is displayed but it's clearly visible. Cannot find module & ...

Rearrange Material UI styles in a separate file within a React project

Currently, I am developing an application utilizing material-ui, React, and Typescript. The conventional code for <Grid> looks like this: <Grid container direction="row" justifyContent="center" alignItems="center&q ...

Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for usi ...

Creating an interface that extends the Map object in TypeScript to maintain the order of keys

After learning that the normal object doesn't preserve key order in TypeScript, I was advised to use Map. Nevertheless, I'm struggling to figure out how to assign values once I've declared the interface. Take a look at my approach: Coding ...

Uploading videos to a single YouTube channel using the YouTube Data API

I have been tasked with creating a node js app for a select group of individuals who need to upload videos. However, our budget is quite limited and we are unable to afford cloud storage services. I am curious if it would be feasible to create a key syste ...

using JavaScript to send numerous text box values to various views

I have a dilemma with passing values between two views. In View1, there are text boxes for entering basic information. After the customer enters this data and clicks on 'add more details', I want to transfer these details to the text boxes in Vie ...

Utilizing React and MaterialUI to create a dynamic GridLayout with paper elements

I am using the react-grid-layout library to create a dynamic grid where each item is a paper component from the React Material UI. However, I encountered an issue while running the application. The browser displayed the error message: "TypeError: react__W ...

Exploring discrepancies in jQuery AJAX responses between Chrome and Firefox

As someone who is not a front-end developer, I find myself working on a casual project that involves using AJAX to retrieve a piece of JSON data. $('#btn1').click(function() { $.ajax({ url: 'http://mywebsite.com/persons/mike&apo ...

React form submissions result in FormData returning blank data

I am having trouble retrieving the key-value pair object of form data when the form is submitted, using the new FormData() constructor. Unfortunately, it always returns empty data. Despite trying event.persist() to prevent react event pooling, I have not ...

Display information in a detailed table row using JSON formatting

I have set up a table where clicking on a button toggles the details of the corresponding row. However, I am having trouble formatting and sizing the JSON data within the table. Is there a way to achieve this? This is how I implemented it: HTML < ...

Creating PopUp Windows with PHP and JavaScript

There is a function created on my page that opens a pop-up window when clicking on a game-mod name: <SCRIPT language="javascript" type="text/javascript"> function popModData( modName ) { var url = "./modList.php?mod=" + modName; ...

Absolute positioned content causing unexpected spacing on top of relative positioned content

I've been experimenting with a fantastic technique by Chris Coyier for implementing full page video backgrounds with content scrolling over the video. However, I've encountered an issue where there's an unexpected gap to the right in Windows ...

Why is applying CSS on an li element using .css() in JQuery not functioning?

Hey there! Could you please review my code? I'm attempting to add a top position to the <li> element using a variable in jQuery, but I'm not sure how to do it. Here's the code: <script> $(document).ready(function(){ ...

Retrieve information filtered based on the query parameter

Utilizing react hooks for dynamic data rendering, I am focusing on two main tasks: a. Extracting URL parameters from the component's history props. b. Retrieving state data from the component's history props, which provides an array of objects ...

Discovering the specific value from a fixture file in Cypress

When I receive a JSON Response, how can I extract the "id" value based on a Username search? For instance, how can I retrieve the response with an "id" value of 1 when searching for the name "Leanne Graham"? It is important to note that the response valu ...

Error encountered with default theme styling in Material-UI React TypeScript components

Currently, I am working on integrating Material-UI (v4.4.3) with a React (v16.9.2) TypeScript (v3.6.3) website. Following the example of the AppBar component from https://material-ui.com/components/app-bar/ and the TypeScript Guide https://material-ui.com/ ...

Utilizing jQuery's each() function to create a seamless loop of background images in a

Struggling with looping the background image in a slick slider? Check out the code snippet below. var json = [ { "img_url": "https://via.placeholder.com/500x500?text=1" }, { "img_url": "https://via.placeholder.com/500x500?text=2" }, { "img_url": "ht ...

The component 'AddPlaceModal' could not be located in the path '~/components/AddPlaceModal.vue'

Recently, I started incorporating Nuxt for Vue into my projects. In an attempt to enhance my page, I added a new component within the /components folder. However, I encountered a warning during compilation: "export 'AddPlaceModal' was not found ...