Steps to automatically make jest mocked functions throw an error:

When using jest-mock-extended to create a mock like this:

export interface SomeClient {
  someFunction(): number;
  someOtherFunction(): number;
}

const mockClient = mock<SomeClient>();

mockClient.someFunction.mockImplementation(() => 1);

The default behavior of functions on the mock is to return undefined if no explicit implementation is provided. For example, calling someFunction will return 1 as expected, but calling someOtherFunction without an implementation will result in undefined.

mockClient.someFunction();      // returns 1
mockClient.someOtherFunction(); // returns undefined

This can lead to unexpected errors in tests, especially with TypeScript where undefined values may not match expected types. To address this issue, one approach is to provide a default implementation for all functions that throws an error when called:

const mockClient = mock<SomeClient>({
  someFunction: jest.fn().mockImplementation(() => {
    throw new Error('someFunction not mocked');
  }),
  someOtherFunction: jest.fn().mockImplementation(() => {
    throw new Error('someOtherFunction not mocked');
  }),
});

However, maintaining this approach becomes cumbersome with multiple functions and requires updating when new functions are added. Is there a simpler way to apply a default mock implementation to all functions in jest?

Answer №1

"jest-mock-extended": "^3.0.4"

A new feature in the 3.0.2 release allows you to set a fallbackMockImplementation for the mock() function. Find more details about this update in PR#110

import { mock } from 'jest-mock-extended';

interface SomeClient {
    someFunction(): number;
    someOtherFunction(): number;
}

test('handling errors when return value is not specified', () => {
    const mockClient = mock<SomeClient>(
        {},
        {
            fallbackMockImplementation: () => {
                throw new Error('not mocked');
            },
        },
    );
    expect(() => mockClient.someFunction()).toThrowError('not mocked');
    expect(() => mockClient.someOtherFunction()).toThrowError('not 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

What methods does node.js use to distinguish between server-side and client-side scripts?

One interesting aspect of PHP is the ability to combine both PHP and JavaScript code within a single file. However, it raises the question: How can we incorporate both server-side and client-side JavaScript code in an HTML file? ...

Tips for preventing HTTP Status 415 when sending an ajax request to the server

I am struggling with an AJAX call that should be returning a JSON document function fetchData() { $.ajax({ url: '/x', type: 'GET', data: "json", success: function (data) { // code is miss ...

Insert the ng-if directive into an element using a directive

I am working on an AngularJS directive that involves looking up col-width, hide-state, and order properties for a flexbox element based on its ID. I want to dynamically add an ng-if=false attribute to the element if its hide-state is true. Is there a way ...

The curly braces in AngularJS are failing to display the values on the HTML page

After trying various articles and solutions to different questions, I am still unable to resolve my issue. I am working on a blank ionic project and it is running smoothly in my browser using ionic serve without any errors. However, instead of displaying ...

Retrieving data from an Array

I've encountered a peculiar issue while working on a test project. It seems that I am unable to access values in an array. pokemonStats$: Observable<PokemonStats[]>; getPokemonStats(id: number): any { this.pokemonStats$ .pipe(take(1)) .subscrib ...

Retrieve all direct message channels in Discord using DiscordJS

I need to retrieve all communication channels and messages sent by a bot. The goal is to access all available channels, including direct message (DM) channels. However, the current method seems to only fetch guild channels. client.channels.cache.entries() ...

What is the best way to showcase a single <ul> list in an infinite number of columns?

Utilizing Django on the backend, I aim to showcase the list below in an unlimited number of columns with overflow-x: auto. <ul class="list"> {% for i in skills %} <li>{{i}}</li> {% endfor %} </ul> Example Result: 1 7 ...

Dealing with errors in Node.js using the Express framework and the

The code I'm having trouble with is shown below app.get('/', function(req, res, next) { if (id==8) { res.send('0e'); } else { next(); } }); app.use(function(err, req, res, next){ res.send(500, ' ...

Utilizing a dynamically created table to calculate the number of neighbors

I have a challenge where I want to create a minesweeper game with numbers indicating how many bombs are nearby. For example, if there are two bombs next to each other and I click on a cell adjacent to them, it should display the number 2. Likewise, if ther ...

Leveraging Typescript Generics for limiting the input parameter of a function

Issue I have developed a Typescript package to share types between my backend node firebase cloud functions and frontend React client that accesses them. Provided below are examples of the types: interface FirstFunctionInput { x: number } interface Sec ...

What is the best method in ASP.NET Boilerplate for retrieving JSON data?

I have been facing an issue while working on this code, constantly running into the error message: Unexpected token o in JSON at position 1 https://i.stack.imgur.com/43Ewu.png I am struggling to troubleshoot and was hoping for some advice or tips on r ...

Why won't JSZip accept a base64 string for loading a zip file?

As I work on implementing a feature where a small JSON object is written to the URL as a user interacts with items on a page, I also want to make sure the URL can be read later so users can resume where they left off. I successfully managed to create the ...

Position the colored div on the left side of the page

Here is the CSS I am currently using... <style type="text/css"> .widediv{width:1366px;margin-left:auto;margin-right:auto} </style> This CSS code helps me create my webpage : <body><div class="widedivv"> <!-- Content go ...

Using React's useEffect and useContext can cause issues with certain components, particularly when dealing with dynamic routes

Currently, I am developing a React blog application where posts are stored in markdown files along with metadata in Firestore. The content .md files are saved in Cloud Storage. In the App component, I utilize useEffect to retrieve the metadata for each pos ...

Tips for adding a string variable to a JQuery HTML element attribute

Hi there, I've been working on a JQuery code to append data to a div element and it's been successful so far. Here is the code: $('#conversation').append('<div id="receiver"><p><b>' + username + ':< ...

Transforming a single object into several arrays

I have a JSON file called "icon.json" that contains the following data: [ { "name": "happy", "url": "1.gif" }, { "name": "excited", "url": "2.gif" }, { "name": "surprised", "url": "3.gif" ...

Transform the arrow function into a standard JavaScript function

Here is the React return code snippet I'm working with: return ( <div className='App'> <form onSubmit={this.submit.bind(this)}> <input value={this.state.input} onChange={(e) ...

Troubleshooting EasyTabs: Localhost Issue with Ajax Tab Configurations

I've implemented EasyTabs for organizing my tabs on a webpage. I decided to use ajax-tabs functionality in order to fetch content from other pages when users click on the navigation menu buttons. However, I've encountered an issue where the conte ...

Using jQuery to locate the href attribute within a TD element with a specific

Update URL <td class="posts column-posts"><a href="edit.php?tshowcase-categories=ops&amp;post_type=tshowcase">2</a></td> Current URL: <span class="view"><a href="https://blog.company.com/team/tshowcase-categories/ops ...

Pass JavaScript variables to a PHP file with the help of AJAX

Hey there, I'm new to developing web-based applications and currently learning about AJAX. I've run into a problem while trying to make an AJAX request with user inputs as variables and fetching the same variables in a PHP file. Below is the code ...