访问Angular 4规范中的静态数据

时间:2017-09-02 16:20:09

标签: angular karma-jasmine

我得到了angular 4 component我希望在组件本身中编写一些specs public searchResponse

以下是我的spec文件

import {async, ComponentFixture, inject, TestBed} from '@angular/core/testing';

import { AppComponent } from './app.component';

import { StoreModule } from '@ngrx/store';

import {myreducer} from '../reducers/myreducer';

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

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [ AppComponent ],

      imports: [
        StoreModule.provideStore({
          myreducer
        }),

      ],

    }).compileComponents();
  }));

  beforeEach(() => {

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();



  });

  it('should create', () => {


  });
});

现在,当我运行ng test时,我得到的问题很简单,我最终得到TypeError: Cannot read property 'searchResponse' of undefined

searchReponse位于AppComponent,如下

export class AppComponent implements OnInit { public searchReponse ; ......

可能导致此问题的任何想法?如果可能的话,我怎样才能将searchReponse作为对象传递?

由于

1 个答案:

答案 0 :(得分:0)

可以通过在规范中对服务响应进行硬编码来实现,如下所示,

describe块中声明一个参数,如下所示

let searchResponse = [
                { 'name': 'ab' },
                { 'name': 'ab' },
                { 'name': 'ab' }
];

单击搜索按钮时,您可以使用以下语句验证测试用例

it('should create', () => {
    fixture.detectChanges();
    let button = fixture.debugElement.nativeElement.querySelector('button');
    button.click();
    expect(component.searchResponse).toBe(searchResponse);

});