I have a Angular2 app with a simple component
@Component({
selector: 'Techs',
template: '',
providers: [HTTP_PROVIDERS]
})
export class Techs {
public techs: Tech[];
constructor(http: Http) {
http
.get('src/app/techs/techs.json')
.map(response => response.json())
.subscribe(result => this.techs = result);
}
}
My tests are executed twice:
Chrome 49.0.2623 (Mac OS X 10.11.4): Executed 0 of 6 SUCCESS (0 secs / 0 secs)
LOG: 'end of test'
Chrome 49.0.2623 (Mac OS X 10.11.4): Executed 6 of 6 SUCCESS (0.182 secs / 0.153 secs)
However if I remove the Http call the test is only executed once
Chrome 49.0.2623 (Mac OS X 10.11.4): Executed 6 of 6 SUCCESS (0.182 secs / 0.153 secs)
Here is my test
describe('techs component', () => {
it('should render 3 elements <tech>', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb
.createAsync(Techs)
.then(fixture => {
fixture.componentInstance.techs = [{}, {}, {}];
fixture.detectChanges();
const techs = fixture.nativeElement;
expect(techs.querySelectorAll('tech').length).toBe(3);
});
}));
});
I think that your problem comes from the asynchronous aspect of your HTTP call. I would see two ways to fix this:
MockBackend
class. Here is to configure it against the XHRBackend
class:
beforeEachProviders(() => {
return [
HTTP_PROVIDERS,
provide(XHRBackend, { useClass: MockBackend }),
];
});
and a way to return what you want in the response:
it('Should return a list of dogs', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: [ { name: 'test' }, ... ]
})));
}
(...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.