【问题标题】:How to test subscribe function in angular onInit method?如何在角度 onInit 方法中测试订阅功能?
【发布时间】:2019-09-24 12:21:24
【问题描述】:

我有以下要测试的组件:

组件:

 constructor(
    private countrystore: Store<CountryAppState>,
    private docstore: Store<DocumentAppState>,
    private formBuilder: FormBuilder,
  ) {}

  ngOnInit() {
    this.getCountryState = this.countrystore.select('selecttimaticCountryState');

    this.getCountryState.subscribe((state) => {
      this.countries = state.response;
    });

规格文件:

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

  Object.defineProperty(window, "matchMedia", {
    value: jest.fn(() => { return { matches: true } })
  });

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        StoreModule.forRoot({}),
        EffectsModule.forRoot([]),
        BrowserAnimationsModule,
        HttpClientModule
      ],
      providers: [
        FormsModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TravellerInfoComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

在我编写测试之前,我收到以下错误:

我看过类似的答案,建议使用 'of' rxjs 运算符来模拟可观察对象,其他人建议使用 spyOn 技术。但我不太明白应该在哪里插入。对测试菜鸟的任何帮助都会很棒。

【问题讨论】:

  • 不要在 beforeEach 中运行 fixture.detectChanges。也不必将第一个/初始 beforeEach 标记为异步。

标签: javascript angular jasmine jestjs


【解决方案1】:
const countrystore = TestBed.get(Store<CountryAppState>);
spyOn(countrystore, 'select').and.callFake(() => {
  return of(someTestDataYouCreate);
});

【讨论】:

    猜你喜欢
    • 2019-02-25
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 2018-09-06
    • 2018-11-19
    相关资源
    最近更新 更多