Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class.

Below is my basic class that returns an object:

            class Producer {
                hello() {
                    return {
                        message:'Class: Hello',
                    }
                }
            }
            export default Producer;

This is the mock class located in the __mocks__ folder:

            class Producer {
                hello() {
                    return {
                        message:'__mocks__: hello',
                    }
                }
            }
            export default Producer;

Now, let's take a look at my test file where everything works as expected:

            import Consumer from './Consumer';
            jest.mock('./Producer');
            test('simple test 1', () => {
                let consumer = new Consumer();
                consumer.call();
                expect(consumer.response.message).toEqual('__mocks__: hello')
                console.log(consumer.response)
                // prints on console { message: '__mocks__: hello' }
            });

The question arises when I need a different response for another test case using the mocked file Producer:

            jest.mock('./Producer').updateOnTheFly( hello() { 
                    return {
                        message:'UPDATE ON FLY: hello',
                    }
            })
            test('simple test 1', () => {

                let consumer = new Consumer();
                consumer.call();
                expect(consumer.response.message).toEqual('UPDATE ON FLY: hello')
            });

Answer №1

When dealing with situations like this, it's best to avoid manually creating a mock at __mocks__/Producer.js.

Instead, utilize jest.mock('./Producer'); to automatically create a mock for the module...

...and then set up the return value for Producer.prototype.hello as necessary:

import Consumer from './Consumer';

import Producer from './Producer';
jest.mock('./Producer');  // <= auto-mock Producer

test('simple test 1', () => {
  Producer.prototype.hello.mockReturnValue({ message: 'mocked: hello' });
  let consumer = new Consumer();
  consumer.call();
  expect(consumer.response.message).toEqual('mocked: hello')  // Success!
});

test('simple test 2', () => {
  Producer.prototype.hello.mockReturnValue({ message: 'UPDATED: hello' });
  let consumer = new Consumer();
  consumer.call();
  expect(consumer.response.message).toEqual('UPDATED: hello')  // Success!
});

Answer №2

After conducting some research, I was able to find a solution to this issue.

        class Producer {
            hello() {
                return {
                    message:' Class: Hello ',
                }
            }
        }
        export default Producer;

When mocking the Producer, there is no need to create a separate mock file.

        import Consumer from './Consumer';
        jest.mock('./Producer');

        test('simple test 1', () => {
            // mocking Producer.hello()
            Producer.mockImplementation(() => {
                return {
                    hello: () => {
                        return {
                            message: "this is mocked "
                        }
                    },
                };
            });  

            let consumer = new Consumer();
            consumer.call(); /// Consume.call() uses inside Producer.hello() mocked
        })            

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

Delay loading of external JavaScript with data attributes

Exploring options for lazy loading this code snippet: <script async src="https://comments.app/js/widget.js?3" data-comments-app-website="TvibSQx_" data-limit="5" data-color="29B127" data-dislikes="1" dat ...

Uploading large files on Vuejs causes the browser to crash

Whenever I try to upload a file using my browser (Chrome), everything goes smoothly for files with a size of 30mb. However, if I attempt to upload a file that is 150mb in size, the browser crashes. The server's maximum upload size has been configured ...

Use the accelerometer in JavaScript and Cordova to control the movement of an object, such as a ball

Having trouble figuring out how to move a ball using the accelerometer. Any tips on combining the accelerometer values with the ball movement? Waiting for accelerometer... <div id="heading">Waiting for heading...</div> <div id="ball" ...

Reduce the size of a webpage by 10%

Have you ever noticed that when you press Ctrl+- on any browser, the page scales down to 90% of its original size? It actually looks nicer at 90%, so I want my webpage to default to opening at 90% instead of 100%. I've tried following common approach ...

Using JavaScript to bring in npm packages

My understanding of javascript modules is still lacking. I recently embarked on a new project that required a library from npm. https://www.npmjs.com/package/random-color-pair After running npm i random-color-pair This created a "node modules" folder wh ...

"Make sure to tick the checkbox if it's not already selected,

Could use some assistance with traversing and logic in this scenario. Here is the logic breakdown: If any checkbox in column3 is checked, then check the first column checkbox. If none in column 3 are selected, uncheck checkbox in column1. If column1 ...

Concatenate a variable string with the JSON object key

I am currently working on a request with a JSON Object structure similar to the following: let formData = { name: classifierName, fire_positive_examples: { value: decodedPositiveExample, options: { filename: 'posit ...

Optimizing SEO with asynchronous image loading

I've been developing a custom middleman gem that allows for asynchronous loading of images, similar to the effect seen on Medium. Everything is functioning smoothly, but I'm uncertain about the impact on SEO. The image tag in question looks like ...

Typescript: Utilizing a generic array with varying arguments

Imagine a scenario where a function is called in the following manner: func([ {object: object1, key: someKeyOfObject1}, {object: object2, key: someKeyOfObject2} ]) This function works with an array. The requirement is to ensure that the key field co ...

What are the best techniques for using jQuery to manipulate an HTML form that contains nested elements?

I have a scenario where I need to dynamically generate mini-forms within an empty form based on certain conditions. For instance, imagine a form that gathers information about restaurants such as their names and locations. Depending on the number of restau ...

Indulging in the fulfillment of my commitment within my Angular element

In my Angular service, I have a method that makes an AJAX call and returns a Promise (I am not using Observable in this case). Let's take a look at how the method is structured: @Injectable() export class InnerGridService { ... private result ...

Convert the Date FR and Date US formats to ISO date format

There is a function in my code that accepts dates in different formats. It can handle two formats: 2022-06-04 or 04/06/2022 I want all dates to be in the format: 2022-06-04 For instance: public getMaxduration(data: object[]): number { data.forEach((l ...

Disabling and enabling a link before and after an AJAX call using jQuery

I have been trying to disable a link before making an ajax call and then re-enable it right after receiving the response. However, my current approach doesn't seem to be working as expected: jQuery(this).prop('disabled', false); Here is my ...

Any suggestions on how to incorporate the variable into the inline JavaScript [[]] API path?

I have a query regarding creating a URL in JavaScript, but I'm unsure how to include variables within th:inline="javascript". Below is my code snippet: <script th:inline="javascript"> $(function() { $('#querySubmit').click(queryS ...

The positioning of the menu icons varies

When it comes to displaying the search icon in the WordPress toggle bar, I use a custom JavaScript file. This setup is mainly focused on website design and menu functionality. Additionally, I have integrated a newsletter subscription plugin for managing su ...

Some elements in the DOM appear to not be rendering even though they are present in the HTML source code

As a newcomer to web development, I have stumbled upon a perplexing issue. In my usage of d3.js (specifically the script found here), I have been attempting to incorporate additional features. I modified my JavaScript code to include a simple <p> ele ...

Is it possible to switch from a dropdown menu to radio buttons?

I am looking to change the dropdown menu in my search section into radio buttons. Currently, when I select something from the dropdown menu, the search fields are altered. Here is the code for the dropdown menu: <select id="qs_category" name="qs_catego ...

Having difficulties accessing the /playlists route with express and app.get in my code

I am encountering a 404 status code error when trying to access app.get('/playlists'). The browser displays "cannot GET /playlists" and I can't seem to figure out why. Here is the code I am using: var express = require('express&apos ...

What is the best way to connect objects that have been separated?

Looking for a way to reattach my detached objects and wondering how to replace the function that currently only triggers an alert. Any suggestions or help is appreciated. http://jsfiddle.net/jy2Zj/ In addition, I have another question - is there a method ...

Is it possible for a nodejs server to handle both grpc and express servers simultaneously, or do they need to be separate servers?

I'm currently in the process of building a REST server using Node/Express. I'm curious about how to incorporate a GRPC server within the same setup. Would it be possible to run both servers on the same NodeJS instance, or is it recommended to hav ...