Having trouble with Jasmine timeout due to asynchronous testing in Angular?

After upgrading a project to Angular 6, some previously successful tests are now failing. Below is an example of one such test:

  beforeEach(
    async(() => {
      TestBed.configureTestingModule({
        declarations: [CampaignsDetailScheduleComponent],
        imports: [
          SomeModule,
          ReactiveFormsModule,
          TranslateModule.forRoot({
            loader: { provide: TranslateLoader, useClass: TranslateFakeLoader }
          }),
          StoreModule.forRoot({})
        ],
        providers: [{ provide: ConfigService, useValue: ConfigServiceMock }],
        schemas: [NO_ERRORS_SCHEMA]
      });
      fixture = TestBed.createComponent(CampaignsDetailScheduleComponent);
      comp = fixture.componentInstance; // Component test instance
      _store = fixture.debugElement.injector.get<Store<State>>(Store);
      comp.campaignModel$ = of(CampaignMockData);
      fixture.detectChanges();
    })
  );

it(
    'close edit schedule modal',
    async(() => {
      spyOn(_store, 'dispatch');
      comp.onClose();
      const args = new ShowHideEditScheduleModal(false);
      expect(_store.dispatch).toHaveBeenCalledWith(args);
    })
  );

This specific test passed without issues before the Angular 6 update. However, it now produces the following error:

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.--Pendng async tasks are: [type: macroTask, source: setInterval, args: {handleId:4072,isPeriodic:true,delay:0,args:[object Arguments],__creationTrace__:[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]},type: macroTask, source: setInterval, args: {handleId:4075,isPeriodic:true,delay:0,args:[object Arguments],__creationTrace__:[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]}]

If anyone has insights on what might be causing this issue, it would be greatly appreciated!

Answer №1

Opt for fakeAsync over async within the before each section.

Answer №2

If you encounter a situation where the default jasmine timeout (which is 5s) is not enough, there are two ways to address it.

it(
    'close edit schedule modal',
    async(() => {
      spyOn(_store, 'dispatch');
      comp.onClose();
      const args = new ShowHideEditScheduleModal(false);
      expect(_store.dispatch).toHaveBeenCalledWith(args);
   // increase default timeout interval to 10s
}), 10000);

Alternatively, you can handle it using the done() method. By incorporating this method, your test will pause until completion. Note that async and done() should not be used together.

it('close edit schedule modal', (done) => {
          spyOn(_store, 'dispatch');
          comp.onClose();
          const args = new ShowHideEditScheduleModal(false);
          expect(_store.dispatch).toHaveBeenCalledWith(args);
          done();
       // increase default timeout interval to 10s
 }, 10000);

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

In search of assistance in delivering HTML form data to a public HTTP service

Seeking assistance with forwarding html form data to a public http service. Any guidance or tutorial recommendations would be greatly appreciated! Below is the structure of my form: <span class="text"> <input class="text" type="text" name="First ...

Unable to redirect using JQuery Ajax post after receiving an ActionResult from an MVC controller

I'm trying to send data from a method to an MVC controller that gives back an action result, and then have my site automatically navigate to the correct view. Here's the code snippet I'm currently working with: function RedirectFunction(ite ...

How to Display a Modal Window Automatically Using Bootstrap.js?

Recently, I've become interested in using the Bootstrap library by Twitter for my simple web page. My goal is to have a modal window automatically display after the page loads. If anyone has any tips on how to achieve this, I would greatly appreciate ...

Struggling to determine the type of constant after a specific type check? (TS2349: Unable to call a function on a type that does not have a call signature

Encountered a puzzling issue with TypeScript where it appears that I should be able to recognize that a constant is an array, and then utilize array methods on it. However, TypeScript seems unable to confirm that a value is truly an array even after a dire ...

The HTML video controls in Safari take precedence over the window.name attribute

When using Safari 8.0.5, the controls attribute for the video element will change the value of window.name to "webkitendfullscreen". This is significant because I rely on using window.name to store client-side data in Safari's private mode, where loca ...

Toggle button to create a fade in/out effect

Below is the HTML code snippet: <html> <head> <Script type = "text/javascript" src = "CprMdlrSrch.js"></Script> <link type="text/css"rel="stylesheet"href="CprMdlrSrch.css"/> </head> <body> <div id=" ...

Navigating in Angular to initiate file retrieval

Is there a way to set up a route in Angular that allows me to download a file? For example, having a route like '/myFile' would result in downloading the file "/assets/files/test.pdf". I've tried using the redirectTo option for routing, bu ...

Utilizing various colors for tooltipFontColor in Chart.js

I'm trying to customize the font color for tooltip labels in Chart.js, but I want to set different colors based on certain conditions. Specifically, I want the label color to be white by default, but change to red if a condition is met. I've look ...

Utilizing Angular CLI configuration for End-to-End testing purposes

I'm currently in the process of updating an Angular CLI project to version 6 The issue I'm facing is that prior to version 6, I could run the command ng e2e -e=e2e and the tests would execute smoothly with the specified environment. However, in ...

Substitute link with asynchronous JavaScript and XML

I need to enable/disable user accounts by clicking on an anchor. The list of users is created dynamically using a loop. Here's an example of an anchor tag: <a href="http://www.example.com/users/deactivate/44" class="btn btn-success" title="Deactiv ...

Is getElementById() returning null?

I'm currently working on a JavaScript program that takes an image URL and displays it on the page by creating an <img> tag. This way, I can easily add multiple images to the page. Here is my code: <!DOCTYPE html> <html lang="en&quo ...

The width of the plotbands on the yAxis of a stacked bar graph is adjusting as the series are dynamically toggled,

https://ibb.co/h7tmwtr https://ibb.co/syRTyPG For the first time, I have included 5 plot bands which looked great. However, when I added a series and toggled it on a stacked bar graph, the plot bands' width started increasing. I want to maintain the ...

TypeScript: "The type is generic and can only be accessed for reading." - Error code 2862

Consider this sample JS function that requires type annotations: const remap = (obj) => { const mapped = {}; Object.keys(obj).forEach((key) => { mapped[key] = !!key; }); return mapped; }; I am attempting to add types using generics (in ...

Certain Array properties cause Array methods to generate errors

I am working with an Array prop in my component's props that is defined like this props: { datasetsList: { type: Array as PropType<Array<ParallelDataset>>, required: false } }, Within the setup() method of my component, I have ...

Document ready not functioning properly for redirects

My code below seems to have an issue as it is not directing to the link specified. <html> <head> <script type="text/javascript" src="<?= baseurl(); ?>/public/js/jquery-1.9.1.min.js"></script> <script type=" ...

The default value of the select option will not be displayed upon loading and will also not appear when another option is selected

I created a form using vue.js that includes a select option dropdown. However, the default value does not display when the form loads, and when a new option is selected from the dropdown, it also does not show. When I use v-for to loop through all options ...

Adjust the hue of a picture rendered on an HTML5 canvas element

Looking at this image, I am wondering: What is the best way to change the entire color of this image to a custom RGB value? Essentially, if I have a grayscale image, how can I convert it back to color by specifying any RGB value? ...

In React/JavaScript, the array variable defined outside the component is having props added to it multiple times

After entering new data, I want to add it to an array called DUMMY_MEALS outside the component and display it as a list. The issue I am facing is that the 'data' object is being added multiple times to DUMMY_MEALS and rendering duplicates on the ...

After the main page is loaded, the div will be dynamically populated with HTML content. How can we confirm that it has finished

I recently took over a project where a page loads and then code attached to that page populates a div with dynamically generated html – essentially filling an existing div with a string of html elements. Within this string are links to images, among oth ...

Utilizing the power of jQuery's $.each method to dynamically generate HTML select options within an AJAX

I am working with a bootstrap modal that includes a form which requires data from the database. To retrieve this data, I am using PHP as shown below: public function get_view_for_inspection_report_belum_eor(){ $q = $this->inspection->get_view_fo ...