Running tests in jest with or without mocks depending on the condition

Currently, I am performing tests using mocks to avoid always hitting APIs. Nevertheless, I also aim to introduce a condition that would allow me to utilize the same test for API testing purposes.

However, when I include a condition, it seems to be disregarded and the mocks are never applied regardless of whether the condition is true or false.

import config from 'config';
if(!config.test.useNetwork) {
    jest.mock('api/companies');
    jest.mock('api/articles');
}

import { searchCompany } from 'api/companies';
...

I have a couple of questions:

  1. Do you have any suggestions on how to implement conditional mocks? I suspect that mocks may not apply because jest.mock needs to be invoked before any imports?
  2. What is typically considered as the best practice for network testing? If I solely rely on mocks, essentially I am only testing the mocks and not the actual network request code. However, omitting mocks means unnecessary API calls are being made.

Answer №1

Firstly:

Ah, the interesting debate about jest.mock() being "hoisted to the top of the code block". But beware, jest.doMock doesn't enjoy the same hoisting privileges. To achieve your goal, consider this approach:

const config = require('./config').default;
if(!config.test.useNetwork) {
    jest.doMock('api/companies');
    jest.doMock('api/articles');
}

const { searchCompany } = require('api/companies');

Secondly:

This question is a bit divisive and may not be suitable for StackOverflow. I'll steer clear of stirring that pot lol

Answer №2

After encountering a similar issue, I stumbled upon a solution that worked for me, and discovered an alternative approach.

In this scenario, utilizing the second parameter (factory) allows you to determine whether to return a mock or the real module.

import config from 'config';
import { searchCompany } from 'api/companies';

jest.mock('api/companies', () => {
  if(!config.test.useNetwork) return jest.genMockFromModule('api/companies');
  return jest.requireActual('api/companies');
});

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

Error: "Tags has not been declared"

Recently, I made some changes to the code within this particular application. Specifically, I added a sidebar in the views/layout.jade file. Within this sidebar, I copied and pasted the code that handles tags from views/index.jade: ul.tags eac ...

how to use jQuery to locate the immediately preceding node that meets specific criteria

How can I locate the nearest parent node above $(this) node that has a specific property such as class="field", without considering parent/child relationships? ...

What is the method for retrieving the name of the currently selected HTML element?

After using jQuery to select certain tags, I am now trying to obtain the name of each tag: $('select, :checkbox, :radio').each(function(){ // ... }); To accomplish this, I have attempted the following code: $('select, :checkbox, :radio ...

Tips for properly formatting large numbers

I am facing a challenge with handling large numbers in my JavaScript code. I came across the nFormatter function for formatting large numbers but I am unsure how to integrate it into my existing code. Below is the nFormatter function that I found: functi ...

Fixing "local storage not defined" issue in vue.js

While attempting to run test cases in vue.js, I encountered an error stating that local storage is not defined. Can anyone provide guidance on resolving this issue? [Login.spec.js] import Login from '../../src/Pages/Login.vue'; import{shallowMo ...

Is it feasible in Angular2 to add CSS to a component using a service?

I have a component named A containing 5 images. Out of the 5, only one image is in color and clickable, while the remaining 4 are greyed out using the CSS class below: .not_opened{ -webkit-filter: grayscale(85%); } The greyscale images are not clickabl ...

Organize a Javascript array by grouping it based on a specific field and

I have an array that I need to group by the createdAt value. [ { "createdAt": "2021-05-17T14:55:29.836Z", "machine": { "label": "MAQ_100", }, }, { "createdAt": "2021-03-10T13:22:45.694Z", "machine": { ...

What are some secure methods for integrating iframes into an Angular 7 project?

Is there a secure method to set the URL for an iframe without bypassing security measures like using this.domsanitizer.bypassSecurityTrustResourceUrl(url)? While this approach may be flagged as a high vulnerability by tools such as Veracode, is there a w ...

Leveraging jQuery for handling button functionality and making asynchronous requests

I am relatively new to working with jQuery, and while there are plenty of resources available on how to bind buttons, I find that my current setup is a bit more complex than what's typically covered. My situation involves: -Using Django to populate ...

What is the best way to create all possible combinations of key-value pairs from a JSON array?

In my scenario, there is a JSON array with key-value pairs where the values are arrays. Here's an example: json = {foo:[1,2],bar:[3,4],pi:[5]} I am looking for a way to generate all possible combinations of these parameters for any number of keys. Th ...

Determine if an option is chosen in multiple select elements using Vanilla JavaScript

In order to determine if a checkbox is checked, we use the following code: let isChecked = event.target.checked But what about multiple select options like the example below? <select name="books[]" multiple> <option value="A">A</option& ...

Having a solid grasp of React and Material UI, as well as familiarity with the concept of props and

For my react application, I utilize Material UI (@mui/material). However, I've come to realize that there might be some nuances in how the components interact with each other. For instance, if I nest a MenuItem inside a Box or a Link inside a Typograp ...

What causes the state hook in react to alter every single property within the object?

I have a list of team members and each member is associated with the same set of applications. I created 2 classes to link each member with their respective applications, resulting in a comprehensive list of all members and applications. This list was init ...

Having trouble finding a solution to prevent code from automatically adding a class in jQuery/JavaScript?

I am currently in the process of customizing the FlexNav Plugin. I have made a modification to allow sub-menus to open on click instead of hover. However, a new issue has arisen where it requires two clicks to open a submenu. Upon investigation, I have i ...

What mistakes am I making in my usage of React hooks in this situation?

As part of my journey through the FullstackOpen course at the University of Helsinki, I am working on creating a simple Phonebook application. In troubleshooting my code, I've noticed that my 'filterBy' state is consistently one step behind, ...

Populating a two-dimensional array with randomly generated numbers using javascript

Apologies if this has been asked before, but I couldn't find any previous posts on the topic as I'm still fairly new to this site! Lately, I've been exploring game development using HTML5 and JavaScript and have gotten into creating tileset ...

What is the process for setting up a subrouter using React Router v6?

This is the current React Router setup I am using: const router = createBrowserRouter([ { path: "/", element: ( <Page activeNav="home" > <Home /> </Page> ) }, { ...

Inspecting every element within an array and indicating a negative outcome if any item is not a string

I'm currently working on a function called 'every' that takes in an array and a callback function as arguments. The purpose of the callback function is to determine if all elements in the array meet a certain condition. In my case, I want th ...

How to insert an HTML element in between multiple list items using jQuery

I have a variety of div elements that I want to group together using jQuery's append method: Here are the initial div elements: <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div& ...

Create HTML content from a file retrieved from the server

I have been working on a dynamic website project, diving into web development from scratch despite having coding experience in general. As I navigate Angular CLI and Bootstrap, I've come across a fundamental question: Do modern websites house all thei ...