What could be the reason that my Jest function mock is interfering with a different test?

Here are some test cases I've encountered:

import { loginPagePresenter } from './LoginPagePresenter'
import { apiGateway } from 'config/gatewayConfig'
import { authRepository } from './AuthRepository'

it('should modify the user in the auth repository with the token, email, and set authenticated observable when a successful API call is made', async () => {
  const authenticatedStub = {
    'success': true,
    'message': 'successful login',
    'email': '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6c7e6c488c5c9cb">[email protected]</a>',
    'token': '123'
  }

  apiGateway.post = jest.fn().mockResolvedValue(authenticatedStub)

  loginPagePresenter.email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f6e4f6d216c6062">[email protected]</a>'
  loginPagePresenter.password = 'aaabbbcom'
  await loginPagePresenter.submit()
  expect(authRepository.user.token).toBe('123')
  expect(authRepository.user.email).toBe('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="721332105c111d1f">[email protected]</a>')
  expect(authRepository.authenticated).toBe(true)
})

it('should not make changes to the user model during an unsuccessful API call', async () => {

  const notAutenticatedStub = {
    'success': false,
    'message': 'bad login',
    'email': '',
    'token': ''
  }

  apiGateway.post = jest.fn().mockResolvedValue(notAutenticatedStub)

  loginPagePresenter.email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a1b3a1854191517">[email protected]</a>'
  loginPagePresenter.password = 'aaabbbcom'
  await loginPagePresenter.submit()
  expect(authRepository.user.token).toBe(null)
  expect(authRepository.user.email).toBe(null)
  expect(authRepository.authenticated).toEqual(false)
})

The behavior of the first test is interfering with the second test. Disabling the first test seems to resolve the issue with the second test. The production code appears to be functioning correctly. However, there seems to be a side effect caused by the mocking function in the first test that prevents the second test from running properly (resetting the returned resolved function may be causing this).

If anyone has insights on how to address this problem, please share.

Answer №1

If you want to ensure a clean slate before running each test, consider adding jest.clearAllMocks() to your test file within a beforeEach() block like this:

import { loginPagePresenter } from './LoginPagePresenter'
import { apiGateway } from 'config/gatewayConfig'
import { authRepository } from './AuthRepository'

beforeEach(() => {
    jest.clearAllMocks();
});

it('should update the auth repository user ...', async () => {
  ...
})

it('should not update the user model when NOT ...', async () => {
  ...
})

This will reset all mocks before each test execution.

You can also individually clear specific mocks using mockFn.mockClear()

To learn more about these methods, check out: jest.clearAllMocks() and mockFn.mockClear()

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

Unable to choose Typescript as a programming language on the VSCode platform

Recently, I encountered an issue while using Visual Studio Code with TypeScript. Even though TypeScript is installed globally, it is not showing up in the list of file languages for syntax highlighting. Despite trying various troubleshooting methods such a ...

Bespoke Socket.io NodeJS chamber

I am currently developing an application involving sockets where the requirement is to broadcast information only to individuals within a specific room. Below is a snippet of the code from my server.ts file: // Dependencies import express from 'expre ...

Retrieve information from Firebase outside of the .on() method

As a newcomer to Typescript, I am struggling to understand how to access the variables latitude1 and latitude2 outside of the this.ref.on('value', (snapshot) function in order to add their values to the locations array. Can anyone provide some gu ...

How can I convert the date format from ngbDatepicker to a string in the onSubmit() function of a form

I'm facing an issue with converting the date format from ngbDatepicker to a string before sending the data to my backend API. The API only accepts dates in string format, so I attempted to convert it using submittedData.MaturityDate.toString(); and su ...

Encountered a runtime error in NgRx 7.4.0: "Uncaught TypeError: ctor is not a

I'm facing difficulties trying to figure out why I can't register my effects with NgRx version 7.4.0. Despite simplifying my effects class in search of a solution, I keep encountering the following error: main.79a79285b0ad5f8b4e8a.js:33529 Uncau ...

Utilizing AWS CDK to Define StackProps Input Variables

Recently, I have started using the AWS CDK and encountered a challenge. I want to allow end users to define custom input variables when using my AWS CDK without having to edit the entire code. While I have been able to work with standard types such as stri ...

Navigating the onSubmit with Formik in React: Tips and Tricks

I have a query regarding my usage of Formik in my React application. Within the onSubmit function, I am making an API call to a service. If this call fails, I want to immediately stop the rest of the submission process without executing any further action ...

There is no such member found in the component declaration, template variable declarations, or element references

Seeking help for a simple fix. The objective is to have the element slide out from the top of the page upon hover. The code is functioning correctly, but I am encountering an error. Error: [Angular] Identifier 'compartmentOpen' is not defined. ...

How can I incorporate an interface and specify a particular type as the return value in TypeScript?

interface Inter{ str:string } function func(){ let v:Inter={ str:'abc' }; return v; } func()//Is there a way to ensure that the type of value returned from `func` is {str:'abc'} without explicitly declaring it i ...

Having trouble with i18n types not functioning correctly in Typescript and Nuxt?

I am currently utilizing NuxtJS/i18n with TypeScript and have included its types in my TS config: { "compilerOptions": { "types": [ "@nuxt/types", "@nuxtjs/i18n", ] } } However, when attempti ...

TypeScript implementation of a reusable component for useFieldArray in React Hook Form

I'm currently working on a dynamic form component using react-hook-form's useFieldArray hook and facing issues with setting the correct type for field. In order to configure the form, I have defined a type and default values: export type NamesAr ...

...additional properties in React function components using TypeScript

Here is a snippet of code that I am working with: <InputComponent id="email" name={formik.values.email} type="text" formik={formik} className="signInInput" disabled/> However, there seems to be an issue with the disable ...

Perform validation for a form field in Angular 2 asynchronously by making an HTTP request

I have a concept where the user can submit a form and if the email is already registered, an error triggered by the API should display. I am using reactive forms with FormBuilder and trying to implement the validator in the subscribe error handler. Constr ...

What strategies can be utilized to extract the structure of JSON files imported via a TypeScript asynchronous function?

Examining the example below: export type AppMessages = Awaited<ReturnType<typeof loadMessages>>; export type Locale = "en" | "fr" | "es"; export const loadMessages = async (locale: Locale) => ({ foo: locale ...

Sticky header in React data grid

Is there a way to implement a sticky header for a data grid in react? I have tried various methods but haven't been able to figure it out. Any suggestions would be appreciated. You can find my code sandbox example here. #react code export const Styl ...

React Form Hook: restoring uniform width to selectors once more

Looking to create a form using React form hooks and Material UI? Check out this link to codesandbox to see the code in action. In the CreateEmployee.tsx file under components\execute folder, you'll find the necessary code. There's also a UI ...

What steps can be taken to resolve the npm package braces problem in react-scripts v2.1.5 if running npm audit does not provide a

I have encountered 63 low vulnerabilities in my NPM package within the react client folder, specifically related to the braces package. These vulnerabilities are mainly present in the jest folder of the react-scripts package version 2.1.5. Despite attempti ...

Snackbar and RTK Query update trigger the error message: "Warning: Cannot update during an existing state transition."

I've built a basic ToDos application that communicates with a NodeJS backend using RTK Query to fetch data, update state, and store cache. Everything is functioning properly as expected with the communication between the frontend and backend. Recently ...

Is there a way for me to bypass adding the label if it already exists in my state, but still include the new value?

I am currently facing an issue with a dropdown select field where I can choose various attribute values. The problem arises when attempting to save the selected data in the state, as the label appears twice and I only require it once. My goal is to exclude ...

What is the proper way to type the SubmitEvent so that the event.target.children property can be accessed

Below is the form I currently have: <form id="search" method="post"> <input type="text" name="query" id="search-field"/> </form> I am looking to add a submit event listener in TypeScript: ...