我正试图在一个组件上编写一些单元测试,该组件将一些服务注入其中,以从服务器加载数据。数据通过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' ].
在相同的单元测试下,很少有其他不依赖于注入服务的测试工作正常。在测试由服务设置的属性时得到"undefined"。有人能帮助我做错了吗?
谢谢
-
需要呼叫
fixture.detectChanges()
才能呼叫ngOnInit
fixture = TestBed.createComponent(MyComponent); fixture.detectChanges();
-
getCountries
返回Promise
,因此您需要then
它,否则allCountries
的值将只是承诺而不是数据getDataFromServer() { this._staticDataServices.getCountries().then(data => { this.countries = data; }); }
-
由于promise是异步的,您需要使用
async
并通过调用fixture.whenStable()
等待异步任务完成import { async } from '@angular/core/testing'; it('...', async(() => { fixture.whenStable().then(() => { expect(comp.allCountries).toEqual(allCountries); }) })
UDPATE
没有看到StaticDataService
,我猜你是试图注入Http
到它。如果没有进一步的配置,这在测试环境中是行不通的。我建议您做的是将服务设置为mock
staticDataService = {
getCountries: jasmine.createSpy('getCountries').and.returnValue(...);
}
providers: [
{ provide: StaticDataService, useValue: staticDataService }
]