简体   繁体   English

如何使用 JEST (Angular Ts) 模拟服务

[英]How to mock a service with JEST (Angular Ts)

Im trying to mock a simple service that returns a Observable for me.我试图模拟一个为我返回 Observable 的简单服务。

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)这就是我的服务(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: ContractClosureService 的 Provider 的配置模块:

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:最后是我的 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.当我尝试 cmd 运行测试时,我遇到了一个笑话错误。 TypeError: this._contractClosureService.getContractClosurePage is not a function类型错误:this._contractClosureService.getContractClosurePage 不是 function

I think that mock is not working to find the reference provided.我认为该模拟无法找到提供的参考。

Any one to help, please?请问有哪位帮忙吗?

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.因为getContractClosurePage是 function 而不是属性值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM