Divide Angular component unit test involving asynchronous tasks

One of my components is responsible for fetching data from a server using a service and then displaying it.

I have created a test for this component which ensures that the data is loaded correctly:

...
it('Should contain data after loading', async(() => {
    fixture.whenStable().then(() => {
        fixture.detectChanges();
        expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle);
        expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph);
        element.querySelectorAll('ul > li').forEach((li, index) => {
            expect(li.textContent.trim()).toBe(expectedListItem[index]);
        });
    });
}));

I am wondering if it's possible to split these expectations into separate it tests?

Here's what I have in mind:

...
describe('Component contains data after loading', async(() => {
    fixture.whenStable().then(() => {
        fixture.detectChanges();

        it('Should contain title', () => {
            expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle);
        });

        it('Should contain paragraph', () => {
            expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph);
        });

        it('Should contain list', () => {
            element.querySelectorAll('ul > li').forEach((li, index) => {
                expect(li.textContent.trim()).toBe(expectedListItem[index]);
            });
        });
    });
}));

However, I encounter an error stating

Argument of type '(done: any) => any' is not assignable to parameter of type '() => void'
at the describe line.

EDIT:

I have included the setup with TestBed.

beforeEach(async(() => {
    serviceMock = prepareServiceMock();
    TestBed.configureTestingModule({
        declarations: [
            TestComponent
        ],
        providers: [
            { provide: TestService, useValue: serviceMock }
        ]
    }).compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
});

Answer №1

To ensure accurate testing, each test spec should be executed independently. It is recommended to include the fixture.detectChanges(); call at the beginning of every new spec.

it('Verifying title', async(() => {
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle);
 }
})); 

it('Validating paragraph content', async(() => {
      fixture.detectChanges();
      fixture.whenStable().then(() => {
      expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph);
    }
})); 

It is essential to create a new Component before each test.

beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
});

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

Displaying FontIcon in a NativeScript alert box

Would it be possible to display a fonticon on a Nativescript dialog? Similar to this example? dialogs.alert({ title: // set icon as text message: "Check-in Successful" }).then(()=> { console.log("Dialog closed!"); }); Is it feasible to ...

Should loaders be utilized in an Angular application?

Webpack configuration allows the use of various loaders, such as file-loader, html-loader, css-loader, json-loader, raw-loader, style-loader, to-string-loader, url-loader, and awesome-typescript-loader. Does Angular have built-in knowledge of loaders with ...

Converting a stringified array object to an object using Expressjs

When working with Angular, I am sending stringified data using FormData. Here is an example: this.formData.append('data', JSON.stringify(this.collections)) Now my challenge is converting this string back to an object in my Express backend. The d ...

What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This ...

Removing an item from an array depending on a specific condition and index

I am working with an array structure that looks like this: [ {key: 4, data: {…}, qText: {…}}, {key: 4, data: {…}, qText: {…}, isVisible: false}, {key: 5, data: {…}, qText: {…}, isVisible: false}, {key: 4, data: {…}, qText: {…}, isVi ...

Issue with a child element that is malfunctioning because of the parent element

There seems to be an issue with the child tag link not working because of the parent tag link. Is there a solution for this problem? Please provide suggestions. Here is the code snippet: <div class="d-flex flex-wrap mx-auto mb-4"> < ...

What could be causing the presence of a "strike" in my typescript code?

While transitioning my code from JavaScript to TypeScript for the first time, I noticed that some code has been struck out. Can someone explain why this is happening and what it signifies? How should I address this issue? Here's a screenshot as an exa ...

Is it possible for Azure static web apps to utilize Azure App Service as their backend?

Is it possible to have a Azure static web app communicate with an existing Azure app service in order for users to download a file generated by the app service? ...

Using the (GoogleMock) mock class as a template parameter

I have recently utilized a class that utilizes the policy design pattern and now I am looking to perform tests on it using googletest/googlemock. For instance, in the code snippet below, I want to conduct tests on class Foo and intend to use a mock class ...

Angular lazy loading routes do not function as intended

I currently have a project that is divided into different modules. Among these modules, the ones that are lazy loaded include the about and contact modules. The navigation menu containing the router links is located in a feature module alongside the header ...

Adjust the page URL during execution of a Protractor test

When conducting my protractor tests, I encountered a scenario where I needed to perform an action on page1 and then navigate to page2 in the same test script to verify the results. describe('something', function() { describe('foo', f ...

Refreshing an Angular page with parameterized routes on IIS results in a blank page

In an effort to resolve the 404 error that occurs when refreshing a page on my Angular application, I made modifications to the web.config file within the website folder on IIS. The code snippet added is shown below: <rule name="AngularJS Routes&qu ...

Migrating the Angular application from version 4.x.x to 6.0

I am currently working on a large open source project built on Angular 4. The project has many components and I am facing challenges in updating it to Angular 6. Even though the official site https://update.angular.io/ provides guidance, manually searchi ...

The Angular2 project using ag-grid-enterprise is currently experiencing difficulties with implementing the License Key

I have a valid license for the ag-grid-enterprise version, but I'm struggling with how to integrate it into my Angular2 project. I've attempted placing the license in the main.ts file using LicenseManager and specifying the enterprise version in ...

Enhancing Angular Material forms with custom background colors

I'm new to Angular and Angular material, still learning the ropes. I have been trying to create a form and needed to change the background color to Red. However, when I attempted to do so, the red color ended up covering the entire form instead of ju ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

What enables typescript to be eligible for transpiling is its equivalent level of abstraction to javascript?

Transpilation is the act of converting code from one language to another with a similar level of abstraction. Can you point out some distinctive characteristics that indicate TypeScript transpires into JavaScript? ...

Switching to Next.js

In my Next JS application, I have a div that dynamically displays the currency and price of a product when a user visits a product page. <div className="flex"> <Image src={EuroCurrency} alt="Euro Sign} /> <h1 className=" ...

Angular firing off select option with object properties

Within my Angular application, I am faced with a situation involving a <select> element that contains a list of <option> elements whose values are associated with objects. My goal is to capture the last selected value using the following code: ...

When utilizing AngularFire with Firebase Firestore Database, users may encounter instances where data duplication occurs on

Currently facing a challenge in my Angular 13.1 Project utilizing @angular/fire 7.4.1 for database management The issue arises consistently across various screens where data from Firestore Database is displayed, particularly on List screens. The lists are ...