Home > front end >  How to mock a service with JEST (Angular Ts)
How to mock a service with JEST (Angular Ts)

Time:07-30

Im trying to mock a simple service that returns a Observable for me.

This is the component that i need to test

  constructor(
    private _contractClosureService: ContractClosureService,
    private _contractClosureState: ContractClosureStateService,
    private _router: Router
  ) {}

  ngOnInit(): void {
    this._contractClosureService
      .getContractClosurePage(true)
      .subscribe((response: any) => {
        this.contractClosurePageResponse = response.services
          .filter((x: any) => typeof x !== undefined)
          .shift();

        this.contractClosureInputUI = this.contractClosurePageResponse?.pages
          .filter((x) => typeof x !== undefined)
          .shift();

        this._contractClosureState.setContractClosureInputUI(
          this.contractClosureInputUI
        );
      });
  }

And that is my service (ContractClosureService)

  getContractClosurePage(
    bruteForce?: boolean
  ): Observable<ServiceContractClosureResponseModel> {
    this._loggerService.log(
      NgxLoggerLevel.INFO,
      'getting getContractClosurePage...',
      `with bruteForce equals ${bruteForce}`
    );
    return this.executeQuery(
      this._contractClosureQuery,
      'contractClosure',
      bruteForce
    );
  }

The config module with the Provider for ContractClosureService:

TestBed.configureTestingModule({
      imports: [
        ApolloTestingModule,
        RouterTestingModule.withRoutes([
          {
            path: CONTRACT_CLOSURE_ROUTES.LANDING_PAGE,
            component: ContractClosureLandingPageComponent,
          },
          {
            path: 'encerrar-contrato/'   CONTRACT_CLOSURE_ROUTES.MAIN,
            component: ContractClosureComponent,
          },
          {
            path: 'encerrar-contrato/'   CONTRACT_CLOSURE_ROUTES.FEEDBACK,
            component: ContractClosureFeedbackComponent,
          },
        ]),
        UiCelescModule,
        LoggerTestingModule
      ],
      declarations: [ContractClosureLandingPageComponent],
      providers: [
        ContractClosureStateService,
        // ContractClosureService,
        { provide: ContractClosureService, useValue: fakeContractClosureService },
        { provide: 'strapiPages', useValue: _strapiPages }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
      .compileComponents();

    _controller = TestBed.inject(ApolloTestingController);
    _contractClosureService = TestBed.inject(ContractClosureService);
    _contractClosureStateService = TestBed.inject(ContractClosureStateService);

  }));

And finally my fakeService:

const fakeContractClosureService = {
    getContractClosurePage: of({
      services: [
        {
          mainTitle: 'Title test',
          mainSubtitle: 'Subtitle test',
          mainIcon: 'icon-test',
          assetInfoTitle: 'Asset info title',
          assetInfoSubtitle: 'Asset info subtitle',
          readingTypeTitle: 'Reading type title',
          readingTypeSubtitle: 'Reading type subtitle',
          sendSectionTitle: 'Send section title',
          sendSectionSubtitle: 'Send section subtitle'
        }
      ]
    }),
  };

When i try to cmd run test im facing a jest error. TypeError: this._contractClosureService.getContractClosurePage is not a function

I think that mock is not working to find the reference provided.

Any one to help, please?

CodePudding user response:

You almost had it, change this:

const fakeContractClosureService = {
    getContractClosurePage: of({

To this:

const fakeContractClosureService = {
    getContractClosurePage: () => of({

since getContractClosurePage is a function and not a property value.

  • Related