Open Closed

ABP ConfigStateservice Error while unit testing in Angular #8505


User avatar
0
KaustubhTasconnect created

ACheck the docs before asking a question: https://abp.io/docs/latest Check the samples to see the basic tasks: https://abp.io/docs/latest/samples The exact solution to your question may have been answered before, and please first use the search on the homepage. Provide us with the following info: 🧐 Hint: If you are using the ABP Studio, you can see all the information about your solution from the configuration window, which opens when you right-click on the solution and click on the Solution Configuration button.

  • ABP Framework version: vX.X.X
  • UI Type: Angular
  • Database System: PostgreSQL
  • Tiered (for MVC) or Auth Server Separated (for Angular): yes/no
  • Exception message and full stack trace:
  • Steps to reproduce the issue:

Hi Team We are working on Unit testing in angular

We have Configured JEST unit Testing framework , and we have write the testcases for one of our component . but we are facing issues regarding ABP core servoces at initilising time .

Our Spec.ts file

import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FinanceDashboardComponent } from './finance-dashboard.component'; import { VinTrackingService } from '../vin-tracking.service'; import { Router, ActivatedRoute } from '@angular/router'; import { DomSanitizer } from '@angular/platform-browser'; import { ConfigStateService, LocalizationService } from '@abp/ng.core'; import { of } from 'rxjs'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { CoreTestingModule, wait } from "@abp/ng.core/testing"; import { ThemeBasicTestingModule } from "@abp/ng.theme.basic/testing"; import { ThemeSharedTestingModule } from "@abp/ng.theme.shared/testing";

describe('FinanceDashboardComponent', () => { let component: FinanceDashboardComponent; let fixture: ComponentFixture; let vinTrackingServiceMock: jest.Mocked; let routerMock: jest.Mocked; let activatedRouteMock: jest.Mocked; let configStateServiceMock: jest.Mocked; let domSanitizerMock: jest.Mocked;

beforeEach(async () => { // Create mocks for services using Jest mock functions let vinTrackingServiceMock = { getPhysicalStatusData: jest.fn(), getOEMFilterData: jest.fn(), getCountryData: jest.fn(), getLetterCreditCount: jest.fn(), getSTLCount: jest.fn(), getBankUtilizationChartData: jest.fn(), getSTLUtilisation: jest.fn(), getLCTRUtilisation: jest.fn(), getPaymentDueChartData: jest.fn(), getActiveBankData: jest.fn(), };

let routerMock = { getCurrentNavigation: jest.fn(), navigate: jest.fn(), };

activatedRouteMock = {
  queryParams: {
    subscribe: jest.fn(),
  },
} as any; // This line ensures that TypeScript understands the structure of `activatedRouteMock`

let configStateServiceMock = {
  getOne: jest.fn(),
};

let domSanitizerMock = {
  bypassSecurityTrustHtml: jest.fn(),
};

await TestBed.configureTestingModule({
  declarations: [FinanceDashboardComponent],
  imports: [
    CoreTestingModule.withConfig(),
    ThemeSharedTestingModule.withConfig(),
    ThemeBasicTestingModule.withConfig(),
  ],
  providers: [
    { provide: VinTrackingService, useValue: vinTrackingServiceMock },
    { provide: Router, useValue: routerMock },
    { provide: ActivatedRoute, useValue: activatedRouteMock },
    { provide: ConfigStateService, useValue: configStateServiceMock },
    { provide: DomSanitizer, useValue: domSanitizerMock },
    { provide: LocalizationService, useValue: {} },
  ],
  schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();

});

beforeEach(() => { fixture = TestBed.createComponent(FinanceDashboardComponent); component = fixture.componentInstance;

// Setup initial mock return values

// configStateServiceMock.getOne.mockReturnValue({ roles: ['user'], id: 'user-id' });

// Mock the subscribe method to simulate queryParams behavior
// activatedRouteMock.queryParams.subscribe.mockImplementation(cb => {
//   // Simulate the queryParams behavior when the component initializes
//   cb({ oemName: 'JLR', country: 'USA' });
//   return { unsubscribe: jest.fn() }; // Simulate an unsubscribe method
// });

// vinTrackingServiceMock.getCountryData.mockReturnValue(of([{ businessEntityId: '1', countryName: 'USA', countryCode: 'US', countryId: 1 }])); // vinTrackingServiceMock.getOEMFilterData.mockReturnValue(of([{ name: 'JLR' }, { name: 'Porsche' }])); vinTrackingServiceMock.getPhysicalStatusData.mockReturnValue(of([{ some: 'data' }])); vinTrackingServiceMock.getLetterCreditCount.mockReturnValue(of({})); vinTrackingServiceMock.getSTLCount.mockReturnValue(of({})); vinTrackingServiceMock.getBankUtilizationChartData.mockReturnValue(of([])); vinTrackingServiceMock.getSTLUtilisation.mockReturnValue(of([])); vinTrackingServiceMock.getLCTRUtilisation.mockReturnValue(of([])); // vinTrackingServiceMock.getPaymentDueChartData.mockReturnValue(of([])); vinTrackingServiceMock.getActiveBankData.mockReturnValue(of([{ some: 'data' }]));

fixture.detectChanges();

});

it('should create the component', () => { expect(component).toBeTruthy(); });

it('should initialize with correct query params', () => { expect(component.oemName).toBe('JLR'); expect(component.country).toBe('USA'); });

it('should call getCountryData and getWidgetDatas on ngOnInit', () => { jest.spyOn(component, 'getWidgetDatas'); component.ngOnInit(); expect(vinTrackingServiceMock.getCountryData).toHaveBeenCalledWith('user-id'); expect(component.getWidgetDatas).toHaveBeenCalled(); });

it('should call getPhysicalStatusData when getWidgetDatas is called', () => { component.getWidgetDatas(); expect(vinTrackingServiceMock.getPhysicalStatusData).toHaveBeenCalled(); });

it('should handle hover events correctly', () => { const item = { oemName: 'JLR' }; const status = { name: 'active' }; component.onHover(item, status, true); expect(component.hoverState['JLR']['active']).toBeTruthy(); component.onHover(item, status, false); expect(component.hoverState['JLR']['active']).toBeFalsy(); });

it('should call reloadComponent when oemFilterClick is called', () => { jest.spyOn(component, 'reloadComponent'); const item = { name: 'Porsche' }; component.oemFilterClick(item); expect(component.reloadComponent).toHaveBeenCalled(); });

it('should update the oemName and reloadComponent when oemName is selected', () => { component.oemName = 'Porsche'; component.selectAllOEM(); expect(component.oemName).toBe('All'); expect(component.reloadComponent).toHaveBeenCalled(); });

it('should call getActiveBankGuaranteeData when getWidgetDatas is called', () => { component.getWidgetDatas(); expect(vinTrackingServiceMock.getActiveBankData).toHaveBeenCalled(); });

it('should return sanitized SVG', () => { const svgString = ''; const sanitized = component.getSanitizedSvg(svgString); expect(sanitized).toBeTruthy(); });

it('should correctly format months in getPaymentDues', () => { const response = [ { month: 'Jan 2024', bankName: 'Bank A', sumOutstandingAmount: 1000 }, { month: 'Feb 2024', bankName: 'Bank B', sumOutstandingAmount: 1500 }, ]; component.generateMonths(response); expect(component.paymentDueChart.length).toBe(12); // Should have 12 months });

it('should redirect to vin-tracking/overview when redirectVin is called', () => { const data = { fieldId: '1', fieldKey: 'key1', controlType: '1', value: 'value1' }; const order = { fieldId: '2', fieldKey: 'key2', controlType: '1', value: 'value2' }; component.redirectVin(data, order); expect(routerMock.navigate).toHaveBeenCalledWith(['/finance/vin-tracking/overview'], { queryParams: { oemValue: 'value1', stauts: 'value2', oemName: 'JLR', country: 'USA' }, state: { legendType: 'PhysicalStatus', activeBankData: { gridId: 'DashabordID', FeildDetails: [ { FieldId: '1', FieldKey: 'key1', ControlType: '1', Value: 'value1' }, { FieldId: '2', FieldKey: 'key2', ControlType: '1', Value: 'value2' } ]} }, }); }); });

Issue We are facimg when we run test case for above spec file

ReferenceError: Cannot access 'ConfigStateService' before initialization

Kindly Provide suggestion on above issue.


1 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Seems like it related to the circular dependency, you can check this

    • https://stackoverflow.com/questions/59665922/referenceerror-cannot-access-service-before-initialization
    • https://github.com/webpack/webpack/issues/12724
Made with ❤️ on ABP v9.1.0-preview. Updated on December 13, 2024, 06:09