サーバーからデータをロードするために、いくつかのサービスが注入されたコンポーネントにいくつかの単体テストを作成しようとしています。データは 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' ].
同じ単体テストの下で、注入されたサービスに依存しない他のいくつかのテストが正常に機能しています。サービスによって設定されたプロパティのテスト中に「未定義」を取得しています。誰かが私がここで間違っていることを助けてもらえますか?
ありがとう