The success or failure of Angular unit tests using TestBed.inject is determined by the order in which the tests are

In my angular application (v11.1.0), I am using Jest for UnitTests. Specifically, I utilize TestBed.inject to obtain a service instance within individual tests and spyOn their methods for testing purposes – whether they have been called or to mock the return values.

However, upon transitioning to TypeScript strict mode, the test fails consistently. Interestingly, rearranging the order of certain tests resolves the issue and everything runs smoothly. It appears that the mocked services are somehow interacting across different unit tests.

Although I attempted to use jest.resetAllMocks(), it did not offer a solution. Below is the code snippet used:

Unit Test

...
// Code snippet unchanged from original
...

Service Mock

...
// Code snippet unchanged from original
...

App Component

this.informationService.getAnnouncementsByType(AnnouncementType.BANNER)
  .pipe(takeUntil(this.destroy$))
  .subscribe(([currentLanguage, banners]) => {
    if (banners?.length > 0) {
      if (banners[0].title) {
        this.maintenanceBannerTitle = banners[0].title[currentLanguage.key as keyof LanguageObject];
      }
      if (banners[0].text) {
        this.maintenanceBannerMessage =
          banners[0].text[currentLanguage.key as keyof LanguageObject];
      }
    }
  });

Answer №1

It is important to restore test-specific spies to a common implementation for all tests in order to prevent test cross contamination. Failure to do so can result in one test affecting the outcome of subsequent tests.

Avoid using jest.resetAllMocks() as it can lead to undesired behavior. When used in a beforeEach block, it resets all spy implementations without exception, turning them into stubs. If specific spy implementations need to be reset, use mockReset() instead.

For a better approach, consider using jest.restoreAllMocks() in a beforeEach block. This function restores all spies created with jest.spyOn to their original implementation, which is generally preferable for all tests and can be configured in Jest settings.

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 are the best methods for individually testing apps within a multi-app project?

I am working on a project with multiple apps. I can easily run each app separately using the command: ng serve --app <appName> -aot. However, I also want to be able to run tests for each individual app in the same way as running them. For example: ...

Angular CLI is operational but unresponsive to input commands

Attempting to incorporate a fresh component into my Angular project, I entered the following command in the console: ng generate component heroes Strangely, while the project is running, Angular does not seem to be acknowledging any commands I input into ...

Angular - Showcasing Nested Objects in JSON

I am experimenting with using angular ngFor to iterate through this data: Link: Although I can successfully retrieve the data by subscribing to it, I encounter an issue when trying to display attributes that contain objects. The output shows as [object O ...

Troubleshooting asynchronous functions in Ionic3 when using Firebase Storage and Firestore

Attempting to retrieve the downloadURL from an uploaded image. The uploadImage function is used to upload the image to Firebase Storage. uploadImage() { this.image = 'movie-' + new Date().getTime() + '.jpg'; let storageRef: any, ...

Exploring TypeScript methods for manipulating Apollo Client query results that have been transformed into props

After following a blog tutorial on GraphQL, I successfully integrated my GraphQL query with a React component to display the returned results. Everything seemed to be working fine as I could log this.props. However, when I tried to access individual data ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

Tips for fixing issues such as "void' is not compatible with a parameter of type '(value: [Post, any, {}[]]) => void'"

Every time I attempt to fetch data in Ionic from Wordpress, I encounter this error: [ng] ERROR in src/app/post/post.page.ts(30,37): error TS2345: Argument of type '(post: Post) => void' is not assignable to parameter of type '(value: [Po ...

The data type is expanding to encompass the entire enumeration

Within the provided code snippet, if the 'as' keyword is omitted in each action, the inferred type for method widens to any of the Kind types. Is there a way to prevent having to repeat 'Kind.PAYPAL as Kind.PAYPAL'? enum Kind { CAS ...

Tips for managing the visibility of raised errors in Firebase functions

Utilizing async/await in my firebase functions poses the challenge of managing potential errors with each call. I am unsure of the best approach to handle catching these errors. Wrapping every call in a try/catch block seems cumbersome given the use of the ...

Encountering a problem with indexing when attempting to include dynamic input text within a form in Angular 6

Whenever I click the "Add" button, a dynamic input text box is added to the form. However, if I remove any input box (except for the last one), the second-to-last input box becomes empty. I'm not sure what the issue might be. Here is the HTML section ...

What is the proper method for integrating a loader into an observable HTTP request?

I need to implement a "loading" variable for my login method: Here is the current login method: public login(authDetails:any):any{ return this.http.post<any>('https://myapi.com/session', authDetails).pipe( map(response => { ...

Is it possible to have Partial<SomeClass> without any methods included?

When creating a class, I like to include a constructor that can accept any relevant members for the class: class AnotherClass { itemA: string; itemB: number; constructor(obj: Partial<AnotherClass>) { Object.keys(obj).forEach(key => this ...

What is the best way to construct an interface in TypeScript with a variable number of properties?

Is it possible to create an interface in typescript with a variable number of string properties, ranging from 5 to potentially 50? ...

Npm Installation Issue (Dependency Resolution Failure)

Whenever I attempt to execute npm install, I encounter the following error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Using a Typescript-specific type within a switch case statement

I'm currently working on a function that, when given an enum value, should return a specific type. I am facing an issue where Typescript does not seem to recognize the properties inside switch and if statements. interface X { x: string; } interface ...

An obstacle encountered when implementing feature module services in a controller for a Nest JS microservice

Recently, I developed a feature module named "user" which includes a controller, model, and services to interact with my postgres database. Despite setting up everything correctly, I encountered an error when trying to call userService from the feature mod ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

When employing Playwright for parallel testing, I have noticed that my tests continue to utilize old credentials rather than obtaining fresh ones when running in parallel mode. The workers do not attempt to fetch

I have a fixture file where I attempt to sign up a new user: import { test as baseTest, request } from '@playwright/test'; import SignUp from '../pages/SignUp'; import fs from 'fs'; import path from 'path'; export * ...

Is it possible to create a function that only accepts a union type if it includes a specific subtype within it?

Is there a way to define the function processArray so that it can handle arrays of type string[], without explicitly mentioning individual types like type1 or type2? For instance, could we indicate this by using arr: type1 | type2? The objective here is t ...

Utilizing a Chrome profile is ineffective in WebdriverIO

Instead of dealing with signing in every time, I prefer pre-signing in on my profile. Even though I am using the code below, it's still not loading in the specified profile. What can I do to resolve this issue? const browser = await remote({ capabi ...