Search code examples
angularrxjsngrxcypress

how do I mock or stub a function in Angular when using Cypress?


Im using Cypress.io as part of the way that Im testing an Angular 7 app. I've combed through the docs, forums and blogs, but I dont see a way to mock or stub a function in Angular. Im trying to mock the employee Observable. I need to have the Employee array contain an employee object so that this.federalTaxesService.loadFederalTaxes() function is called. In production, this app gets the Employee array from the NgRx store, but the store is not working correctly when using Cypress for some reason.

export class EmployeeTaxDetailsContainerComponent implements OnInit, OnDestroy {
  watchEmployee$: Subscription;
  watchFederalTaxes$: Subscription;

  federalTaxes$: Observable<any> = this.federalTaxesService.federalTaxes$;
  employees$: Observable<any> = this.employeesService.employees$;

  federalTaxes: FederalTaxes;
  employeeUuid: string;

  constructor(public employeesService: EmployeesFacade, public federalTaxesService: FederalTaxesFacade) {}

  ngOnInit() {
    this.watchEmployee$ = this.employees$.subscribe((employees: Employee[]) => {
      if (employees && employees.length > 0) {
        this.employeeUuid = employees[0].uuid;
        this.federalTaxesService.loadFederalTaxes(this.employeeUuid);
      }
    });

    this.watchFederalTaxes$ = this.federalTaxes$.subscribe((federalTaxes: FederalTaxes) => {
      if (federalTaxes) {
        this.federalTaxes = federalTaxes;
      }
    });
  }

  ngOnDestroy() {
    if (this.watchFederalTaxes$) {
      this.watchFederalTaxes$.unsubscribe();
    }
    if (this.watchEmployee$) {
      this.watchEmployee$.unsubscribe();
    }
  }
}

Solution

  • I didnt end up trying to mock the Observable. Most of that code is covered in my unit tests. What I really needed was to have this.federalTaxes have a value, which is what the code below does.

    cy.get('.some-ng-element').then(($el) => {
        const el = $el[0].parentElement;
        const win = el.ownerDocument.defaultView;
        const component = win.ng.probe(el).componentInstance;
        component.federalTaxes = { additionalWithholding: 22299, allowances: 1, filingStatus: 'Single' };
    });