2

我正在尝试在一个组件上编写一些单元测试,将一些服务注入其中,以从服务器加载数据。数据通过 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' ].

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

谢谢

4

1 回答 1

0
  1. 您需要调用fixture.detectChanges()ngOnInit调用的。

    fixture = TestBed.createComponent(MyComponent);
    fixture.detectChanges();
    
  2. getCountries返回 aPromise所以你需要then它,否则 valueallCountries将只是 promise 而不是 data

    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);
      })
    })
    

UDPATE

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

staticDataService = {
  getCountries: jasmine.createSpy('getCountries').and.returnValue(...);
}

providers: [
  { provide: StaticDataService, useValue: staticDataService }
]
于 2016-10-16T16:13:03.643 回答