如何模拟一个Observable?我试图以三种不同的方式嘲笑它

问题描述 投票:0回答:2

我已经编写了许多单元测试来测试可观察量,但由于某种原因,这个测试不像我写的其他测试那样,但是我没看到问题是什么。

我想要一个模拟ChangePasswordFacade.successful $来返回一个返回true的Observable。尽管我以前使用过下面的模拟策略,但它不起作用。我尝试将ChangePasswordFacade注入测试。我尝试在TestBed提供程序的useValue中使用模拟成功的$函数。我尝试了下面的方法。它们都是虚假的成功美元。我怎么能以不同的方式嘲笑这个以回归呢?

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PasswordChangeModalComponent } from './password-change-modal.component';
import { ReactiveFormsModule } from '@angular/forms';
import { PasswordChangeFormComponent } from '../../..';
import { DefaultPopoverComponent } from '@bis-angular/shared-components/pattern-library';
import { Store, StoreModule } from '@ngrx/store';
import {
  ChangePasswordFacade,
  UserInformationFacade,
  changePasswordInitialState,
  CHANGEPASSWORD_FEATURE_KEY,
  changePasswordReducer
} from '@bis-angular/users';
import { configureTestSuite } from 'ng-bullet';
import { of } from 'rxjs';

describe('PasswordChangeModalComponent', () => {
  let component: PasswordChangeModalComponent;
  let fixture: ComponentFixture<PasswordChangeModalComponent>;

  const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
  const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);

  const changePasswordFacadeSpy = jasmine.createSpyObj('ChangePasswordFacade', ['resetState']);

  configureTestSuite(() => {
    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        StoreModule.forRoot({}),
        StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer, {
          initialState: changePasswordInitialState
        })
      ],
      declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
      providers: [Store, UserInformationFacade, ChangePasswordFacade]
    });
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(PasswordChangeModalComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    component.defaultPopoverComponent = childDefaultPopoverComponent;

    component.watchSuccessful = { unsubscribe: () => {} };
    spyOn(component.watchSuccessful, 'unsubscribe');
    const service = TestBed.get(ChangePasswordFacade);
    spyOn(service, 'successful$').and.returnValue(of(true));
  });


  describe('showPasswordChangeModal function ', () => {
    it('should call showModal and then not hide if not successful  ', () => {
      spyOn(component, 'hidePasswordChangeModal');
      component.successful$.subscribe((successful: boolean) => {
        expect(component.hidePasswordChangeModal).toHaveBeenCalled();
        expect(changePasswordFacadeSpy.resetState).toHaveBeenCalled();
        expect(component.watchSuccessful.unsubscribe).toHaveBeenCalled();
      });
      component.showPasswordChangeModal();
      expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
    });
  });


});
import { Injectable } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { ChangePasswordPartialState } from './change-password.reducer';
import { changePasswordQuery } from './change-password.selectors';
import { ChangePassword, ChangePasswordResetState } from './change-password.actions';
import { NewPassword } from '@bis-angular/users';

@Injectable()
export class ChangePasswordFacade {
  successful$ = this.store.pipe(select(changePasswordQuery.getSuccessful));

  initiated$ = this.store.pipe(select(changePasswordQuery.getInitiated));

  constructor(private store: Store<ChangePasswordPartialState>) {}

  changePassword(newPassword: NewPassword, userId: string) {
    this.store.dispatch(new ChangePassword(newPassword, userId));
  }

  resetState() {
    this.store.dispatch(new ChangePasswordResetState());
  }
}
angular unit-testing karma-jasmine rxjs6
2个回答
0
投票

这是我如何做到的:我使用商店发送一个动作来将成功的$改为true。现在它是一个集成测试,而不是单元测试。

import { ChangePasswordFacade, UserInformationFacade } from '@bis-angular/users';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { StoreModule, Store } from '@ngrx/store';
import { PasswordChangeModalComponent, PasswordChangeFormComponent } from '../../..';
import * as fromFeature from '@bis-angular/users';
import { ReactiveFormsModule } from '@angular/forms';
import { configureTestSuite } from 'ng-bullet';
import { DefaultPopoverComponent } from '@bis-angular/shared-components/pattern-library';

describe('PasswordChangeModalComponent', () => {
  let component: PasswordChangeModalComponent;
  let fixture: ComponentFixture<PasswordChangeModalComponent>;
  let store: Store<fromFeature.ChangePasswordState>;

  const childDefaultPopoverComponent = jasmine.createSpyObj('DefaultPopoverComponent', ['hideModal', 'showModal']);
  const childPasswordChangeFormComponent = jasmine.createSpyObj('PasswordChangeFormComponent', ['setFormControlsToEmpty']);

  configureTestSuite(() => {
    TestBed.configureTestingModule({
      imports: [
        StoreModule.forRoot({}),
        ReactiveFormsModule,
        StoreModule.forFeature(fromFeature.CHANGEPASSWORD_FEATURE_KEY, fromFeature.changePasswordReducer, {
          initialState: fromFeature.changePasswordInitialState
        })
      ],
      declarations: [PasswordChangeModalComponent, DefaultPopoverComponent, PasswordChangeFormComponent],
      providers: [ChangePasswordFacade, UserInformationFacade]
    });
  });

  beforeEach(() => {
    store = TestBed.get(Store);
    spyOn(store, 'dispatch').and.callThrough();

    fixture = TestBed.createComponent(PasswordChangeModalComponent);
    component = fixture.componentInstance;
    component.defaultPopoverComponent = childDefaultPopoverComponent;
    component.watchSuccessful = { unsubscribe: () => {} };

    spyOn(component.watchSuccessful, 'unsubscribe');
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });


  describe('showPasswordChangeModal function ', () => {
    it('should call showModal and then hide if successful  ', () => {
      spyOn(component, 'hidePasswordChangeModal');
      spyOn(component.changePasswordService, 'resetState');
      const action = new fromFeature.ChangePasswordSuccessful({});

      store.dispatch(action);
      component.showPasswordChangeModal();

      component.successful$.subscribe((successful: boolean) => {
        expect(component.hidePasswordChangeModal).toHaveBeenCalled();
        expect(component.changePasswordService.resetState).toHaveBeenCalled();
      });
      expect(childDefaultPopoverComponent.showModal).toHaveBeenCalled();
    });
  });
});

-1
投票

因为,您想要访问successful$,它是在ChangePasswordFacade的类级定义的。

就像是:

export class ChangePasswordFacade{
   successful$:observable // ... something like this
}

你应该尝试useValue

 configureTestSuite(() => {
    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        StoreModule.forRoot({}),
        StoreModule.forFeature(CHANGEPASSWORD_FEATURE_KEY, changePasswordReducer, {
          initialState: changePasswordInitialState
        })
      ],
      declarations: [PasswordChangeFormComponent, DefaultPopoverComponent, PasswordChangeModalComponent],
      providers: [Store, UserInformationFacade, 
                   {provide: ChangePasswordFacade , useValue: 
                     {
                         successful$ : of(true)
                     }
                   }'
                 ]
    });
  });
© www.soinside.com 2019 - 2024. All rights reserved.