Transitioning from es2016 to es2018 or later versions may cause fakeAsync tests to encounter failures

I have been working on upgrading my project and wanted to make sure I was using the latest ECMAScript version.

In my tsconfig.spec.json files, I originally had es2016, but I decided to try updating it to 2018 and even experimented with es2022.

After changing versions, most of my tests passed without any issues. However, there are a few that now fail. One specific case is a method that closes and destroys a modal.

  async destroyModal(): Promise<void> {
    const { modalComponentType, modalComponentRef } = this._state$.value;
    document.querySelector('dialog')?.close();
    this.setState({ modalComponentType, modalComponentRef, modalOpen: false }, ModalStateActions.CloseModal);

    // Wait for 300ms for animation before proceeding
    await new Promise(resolve => setTimeout(resolve, 300));

    // Clear the modal container and notify observers
    this.resetModal();
  }

For testing purposes, I have the following test:

  it('should destroy modal on esc press', fakeAsync(() => {
    service.initModalContainer(hostComponent.componentInstance.viewContainerRef);
    service.createModal(DummyComponent).then(() => verifyModalCreated());
    tick();
    dispatchEscPressEvent();
    tick(500);
    verifyModalDestroyed();
  }));

With es2016, the test works as expected by simulating the passage of time and then calling verifyModalDestroyed(). However, with es2018 or es2022, the test fails before the Promise resolves inside the destroyModal() method. It seems like the tick() function no longer has an effect after the update.

Could someone please help me understand what changes between the ECMAScript versions could be causing these test failures?

Answer №1

It seems that the async/await feature is causing issues in versions es2018 and above, leading to challenges when testing this type of function. There are alternative methods to test such functions. One approach is to implement the test case using async/await, while another option involves utilizing then in conjunction with the done argument of the test case. The done signal indicates when the test case has completed.

it('should destroy modal on esc press', async () => {
  spyOn(component, 'resetModal');
  await component.destroyModal();
  expect(component.resetModal).toHaveBeenCalled();
});

it('should destroy modal on esc press', (done) => {
  spyOn(component, 'resetModal');
  component.destroyModal().then(() => {
    expect(component.resetModal).toHaveBeenCalled();
    done();
  });
});

Check out the Stackblitz Demo

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

When you press multiple buttons, the correct button will reveal an image while the incorrect buttons will display an X

Could you lend a hand with the code below? Your assistance is truly appreciated :). Thank you in advance. I need help setting up a functionality where clicking on the correct button (e.g. H) will display a checkmark and a forward link image. If the user c ...

Unable to send JSON data from server to client following a successful file upload operation

I'm currently working on a project that involves NodeJS, Express, JQuery, and Typescript. The issue I'm facing is related to uploading a file from the front end, which is successful. However, I'm encountering difficulties in returning a JSON ...

Angular 2 - Inconsistent Data Persistency in Service

Reviewing the following code snippet, it can be seen that the CartService class contains a Cart class. The addToCart() function is used to store CartItem(s) in the cart and then display them in the console to demonstrate the functionality. xxxxxxxxxxxxxxx ...

What is the best way to conduct tests on React components' methods and ensure they are integrated into my Istanbul coverage report

Is there a way to test the methods of react components and include them in my Istanbul test coverage? Edit: I'm using enzyme. Just wanted to mention that. Take, for instance, this component: class SearchFormContainer extends Component { static h ...

Guide to extracting information from a text file, modifying the content, and then adding it to an HTML document

I have some content stored in a text file which includes HTML with template literals like the following: <html> <head></head> <body> <p>`${abc}`</p> </body> </html> The values are coming from server abc.. M ...

Uncover and control nested objects in JSON data

Having a dynamic foo object with the possibility of nested parent objects raises the question of how to effectively: 1) Determine the last object that has a parent? 2) Create an array containing all nested parent objects along with the initial obj (foo.o ...

Removing repetitive strings from an array in the most efficient manner

We've successfully developed a script to eliminate duplicate strings from an array while preserving the order necessary for angular's ng-repeat loop. It's also important that the remaining elements maintain their original index. scope.feedb ...

The process of obtaining an observable from a service

I'm having trouble figuring out how to return the observable back to the component after printing it in the console with my service code. Here is a snippet of my service code: const visit$ = this.db.object('visitordetails/'+$key); this.ite ...

Require a Single Error Message When Two Fields Are Left Blank

I've been working on an asp.net contact form that includes fields for 'Tel No.' and 'Email'. I'm trying to set up one error message for when both of these fields are left blank upon form submission, but I just can't seem ...

Tips for setting up Nginx with Node.js on a Windows operating system

I am looking to set up Nginx on my Windows machine in order to run two node applications. Can anyone provide guidance on how to accomplish this? I have attempted to download Nginx 1.6.3, but have had trouble finding instructions specifically for running i ...

A versatile Material UI paper that adjusts its dimensions dynamically

Utilizing Material-UI's Paper component (https://mui.com/components/paper/), I've encountered a scenario where the content within the Paper element needs to be dynamic. <Paper className="modal" elevation={3}> ...Content </Paper ...

Comparing the Impact of Queries and Filters on Performance in MongoDB and Node.js

There are two methods I am using to calculate the count of documents based on their status. Here are the two methods: collection.find({ Status: 'pending' }).count(function (e, pending) { collection.find({ Status: 'open' }).count(functi ...

The navigation buttons in Flexslider can't be seen when hovered over, accompanied by an orange box

Currently, I am incorporating FlexSlider 2 into a WordPress website. I am facing an issue where the back and forth navigation buttons are not functioning properly. The back navigation button appears as just an orange box, and the forward navigation button ...

I'm experiencing an issue with redirect in Nextjs that's causing an error message to appear. The error reads: "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I'm currently diving into the world of NextJS and working on creating a simple recipe application. Utilizing the new App Router has been smooth sailing for the most part, except for one hiccup with the login function. After successfully logging in (us ...

How to fetch files using URL in JavaScript

I need a solution for automatically downloading multiple PDF files from Google Drive and Docs using their URLs with JavaScript code. I don't want to manually go to each link to download the files. Although I've researched various answers on Stac ...

After switching over to Angular 6 from Angular 5, it's been noticed that the Bootstrap button styles are lacking proper

We recently completed an upgrade from Angular 5 to Angular 6. The problem: After the upgrade, we noticed that Bootstrap button styles no longer have any margin spacing between them. Current Bootstrap Version: 3.3.7 For instance, if you have the followin ...

Mouseover feature for image is functioning, but having issues with alignment

I am currently working on displaying images upon mouse over actions. While the functionality is working perfectly, I am facing an issue where the displayed images appear below and the last image takes up space at the bottom. To rectify this problem, I woul ...

When Ajax attempts to run a PHP page, it redirects me to a different page

My goal is to create a live chat feature using PHP, MySQL, and AJAX. I have almost got it working perfectly, but I'm stuck on how to submit the chat message without refreshing the page. I have a PHP page called sendchat.php that takes input data and s ...

WebDriverError: The preference value for network.http.phishy-userpass-length in Firefox is not valid: exceeds maximum allowed length

Attempting to initiate a new test case using gecko driver (v0.15) with a specific Firefox profile in Protractor 5.1.1. I created the profile based on this guidance: Set firefox profile protractor Upon starting the execution through the protractor configur ...

Utilize nodemailer in Angular 6 to effortlessly send emails

I am currently experiencing an issue with my email service form in my Angular 6 application integrated with Node.js. I have set up the form using Bootstrap and Nodemailer for sending emails, but it seems to not be working as expected. Whenever I attempt to ...