首页 > 解决方案 > Jasmine Karma - 未捕获的错误:macroTask 'setInterval':无法转换到 'running',期待状态 'scheduled',是 'notScheduled'

问题描述

我正在使用带有 Zone.js 的 Angular 7:~0.8.26。在我的 test.ts 文件中,我导入了 import 'zone.js/dist/zone-testing'; 我的规格文件是:

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { CUSTOM_ELEMENTS_SCHEMA, DebugElement } from '@angular/core';
import { async, fakeAsync, flushMicrotasks, tick, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatAutocompleteModule, MatDatepickerModule, MatNativeDateModule } from '@angular/material';
import { By } from '@angular/platform-browser';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { CustomPipesModule } from 'shared/custom-pipes.module';
import { GoogleAutocompletePrediction } from 'shared/models';
import { DataService } from 'shared/services/data.service';
import { GoogleMapsService } from 'shared/services/google-maps.service';
import { I18nConstantsService } from 'shared/services/i18n-constants.service';
import { InsuranceService } from 'shared/services/insurance.service';
import { MockI18nModule } from 'shared/specs/mocks/I18n/mock-i18n.module';
import { MockDataService } from 'shared/specs/mocks/mock-data.service';
import { mockAutocompletePrediction, MockGoogleMapsService } from 'shared/specs/mocks/mock-google-maps.service';
import { MockInsuranceService } from 'shared/specs/mocks/mock-insurance.service';
import { AsInsuranceInformationComponent } from './as-insurance-information.component';

const debounceTime = 200;
const mockPredictions = new Array(5).fill(new GoogleAutocompletePrediction());

describe('AsInsuranceInformationComponent', () => {
  let component: AsInsuranceInformationComponent;
  let fixture: ComponentFixture<AsInsuranceInformationComponent>;
  let insuranceService: InsuranceService;
  let googleService: GoogleMapsService;
  let dataService: DataService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AsInsuranceInformationComponent],
      imports: [RouterTestingModule,
        HttpClientTestingModule,
        MatAutocompleteModule,
        FormsModule,
        ReactiveFormsModule,
        CustomPipesModule,
        MockI18nModule,
        MatDatepickerModule,
        MatNativeDateModule],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [I18nConstantsService,
        { provide: InsuranceService, useClass: MockInsuranceService },
        { provide: GoogleMapsService, useClass: MockGoogleMapsService },
        { provide: DataService, useClass: MockDataService }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    googleService = TestBed.get(GoogleMapsService);
    insuranceService = TestBed.get(InsuranceService);
    // dataService = TestBed.get(DataService);
    fixture = TestBed.createComponent(AsInsuranceInformationComponent);
    component = fixture.componentInstance;
    component.insuranceProviders = [{
      insuranceCompanyName: 'LAB CARD',
      insuranceMnemonic: 'LBCRD'
    }, {
      insuranceCompanyName: 'MEDICARE',
      insuranceMnemonic: '3500'
    }, {
      insuranceCompanyName: 'NJ MEDICARE',
      insuranceMnemonic: '3500'
    }, {
      insuranceCompanyName: 'RAILROAD RETIREES MEDICARE',
      insuranceMnemonic: '3700'
    }, {
      insuranceCompanyName: 'TRAVELERS RAILROAD MEDICARE',
      insuranceMnemonic: '3700'
    }, {
      insuranceCompanyName: 'BC/BS OF NEW JERSEY/HORIZON',
      insuranceMnemonic: '4000'
    }, {
      insuranceCompanyName: 'BLUE CROSS & BLUE SHIELD OF NEW JERSEY',
      insuranceMnemonic: '4000'
    }];
    fixture.detectChanges();
  });
  fdescribe('auto complete diff address', () => {
    beforeEach(
      fakeAsync(() => {
        component.form.get('sameas').patchValue(true);
        component.blnInsuranceHolder = true;
        fixture.detectChanges();
        tick(debounceTime);
        debugger;
        component.form.get('differentPersonalAddress').get('city').patchValue('Huntsville');
        component.form.get('differentPersonalAddress').get('state').patchValue('AL');

      }));

    it(
      'debounces the input',
      fakeAsync(() => {
        const spy = spyOn(googleService, 'getGoogleCityState').and.returnValue(of());
        const sampleZip = '45040';
        component.form.get('differentPersonalAddress').get('zipCode').patchValue(sampleZip);
        fixture.detectChanges();
        tick(debounceTime);
        expect(googleService.getGoogleCityState).toHaveBeenCalledTimes(1);
        expect(googleService.getGoogleCityState).toHaveBeenCalledWith(sampleZip);
      })
    );

   it(
      'does autofill city and state',
      fakeAsync(() => {
        component.form.get('zipCode').patchValue('45040');
        fixture.detectChanges();
        tick(debounceTime);
        expect(component.form.get('city').value).toEqual('Huntsville');
        expect(component.form.get('state').value).toEqual('AL');

      })
    );

  });

});

我在chrome中不断收到此错误:

Uncaught Error: macroTask 'setInterval': can not transition to 'running', expecting state 'scheduled', was 'notScheduled'.

在控制台中,我看到堆栈被递归地填满了错误。

组件文件有这个功能,这是我要测试的:

  zipCodeValidationDiffAddressInit() {
    this.form
      .get('differentPersonalAddress')
      .get('zipCode')
      .valueChanges.pipe(
        takeUntil(this.destroy$),
        debounceTime(200),
        filter(zipCode => {
          return zipCode.length > 4;
        }),
        switchMap(zipCode => this.googleMapService.getGoogleCityState(zipCode))
      )
      .subscribe((response: any) => {
        response = this.googleMapService.getCityStateFromAddressResponse(response);
        if (response && response.city && response.state) {
          this.cityFromAPI = response.city;
          this.stateFromAPI = response.state;
          this.form
            .get('differentPersonalAddress')
            .get('city')
            .patchValue(response.city);

          const isInUSA = !!this.states.filter(state => state.value === response.state).length;

          if (isInUSA) {
            this.form
              .get('differentPersonalAddress')
              .get('state')
              .patchValue(response.state);
          } else {
            this.form
              .get('differentPersonalAddress')
              .get('state')
              .patchValue(null);
            this.form
              .get('differentPersonalAddress')
              .get('zipCode')
              .setErrors({ outsideUsa: true });
          }
        } else {
          this.form
            .get('differentPersonalAddress')
            .get('zipCode')
            .setErrors({ invalidzipCode: true });
        }
      });
  }

任何想法将不胜感激。

标签: angulartypescriptunit-testingjasminekarma-jasmine

解决方案


有类似的问题。将 zone.js 升级到 0.8.29 可以正常工作。


推荐阅读