Angular2最终版本:单元测试下的注入服务方法返回undefined

时间:2016-10-16 16:02:33

标签: unit-testing angular typescript jasmine spyon

我正在尝试在注入了一些服务的组件上编写一些单元测试,以从服务器加载数据。数据在OnInit()方法中加载到此组件中。我正在尝试使用spyOn服务方法返回一些虚拟数据。以下是单元测试设置 -

let comp: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let staticDataService: any;
let spy: jasmine.Spy;
let allCountries: string[];

describe('MyComponent', () => {
beforeEach( async(() => {

    TestBed.configureTestingModule({
        imports : [ FormsModule, HttpModule ],
        declarations : [MyComponent],
        providers: [ StaticDataService ]
    })
    .compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    comp = fixture.componentInstance;
    staticDataService = fixture.debugElement.injector.get(StaticDataService);
    allCountries = [] = ["US", "UK"];
    spy = spyOn(staticDataService, 'getCountries').and.returnValue(Promise.resolve(allCountries));
    });
it('Countries should be set', () => {
    expect(comp.allCountries).toEqual(allCountries);
    }); 
});

以下是我正在进行单元测试的组件类 -

@Component({
  moduleId: module.id,
  selector: 'myeditor',
  templateUrl: 'my.component.html',
  styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
  allCountries: string[];
  constructor(private _staticDataServices: StaticDataService) {}
  ngOnInit() {
    this.getDataFromServer();
  }

  getDataFromServer()
  {
    this.allCountries = this._staticDataServices.getCountries();
  }

我收到以下错误 -

    Chrome 53.0.2785 (Windows 7 0.0.0) MyComponent Countries should be set FAILED
    [1]     Expected undefined to equal [ 'US', 'UK' ].

在相同的单元测试下,很少有其他测试工作正常,这些测试不依赖于注入的服务。在测试服务设置的属性时获取“未定义”。 有人可以帮助我在这里做错了吗?

由于

1 个答案:

答案 0 :(得分:0)

  1. 您需要拨打fixture.detectChanges()来呼叫ngOnInit

    fixture = TestBed.createComponent(MyComponent);
    fixture.detectChanges();
    
  2. getCountries返回Promise,因此您需要then,否则allCountries的值只是承诺而不是数据

    getDataFromServer() {
      this._staticDataServices.getCountries().then(data => {
        this.countries = data;
      });
    }
    
  3. 由于promise是异步的,您需要使用async并等待异步任务完成,方法是调用fixture.whenStable()

    import { async } from '@angular/core/testing';
    
    it('...', async(() => {
      fixture.whenStable().then(() => {
        expect(comp.allCountries).toEqual(allCountries);
      })
    })
    
  4. UDPATE

    在没有看到StaticDataService的情况下,我猜你正试图将Http注入其中。如果没有进一步配置,这将无法在测试环境中工作。我建议你做的只是让服务成为模拟

    staticDataService = {
      getCountries: jasmine.createSpy('getCountries').and.returnValue(...);
    }
    
    providers: [
      { provide: StaticDataService, useValue: staticDataService }
    ]