2
我想窺探Http
服務,看看它是否調用正確的端點。有可能這樣做嗎?Angular2茉莉花spyOn http調用
到目前爲止,在我的服務中,我測試的所有數據都是他們發回數據......我想讓它們更有用。
如果你需要它,這是我目前的規範文件:
import { TestBed, async, inject } from '@angular/core/testing';
import { SignupService } from './signup.service';
import { Observable } from 'rxjs/Observable';
import { HttpModule, Http, Response, ResponseOptions, RequestOptions, Headers, XHRBackend } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { ErrorHandlerService } from '../../services/error-handler.service';
describe('SignupService',() => {
let errorStub = {};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
SignupService,
{ provide: XHRBackend, useClass: MockBackend },
{ provide: ErrorHandlerService, useValue: errorStub }
]
});
});
it('signup should return an application error if no apps are provided', inject([SignupService], (service: SignupService) => {
service.signup('', [], null).subscribe(
suc => { },
err => expect(err).toMatch(/application/)
);
}));
it('signup should return a role error if no roles are provided', inject([SignupService], (service: SignupService) => {
service.signup('', null, []).subscribe(
suc => { },
err => expect(err).toMatch(/rôle/)
);
}));
it(
'signup should return a response with a "contenu" parameter',
inject([SignupService, XHRBackend], (service: SignupService, mockBackEnd: MockBackend) => {
let content = 'anything';
mockBackEnd.connections.subscribe((connection: MockConnection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify({
contenu: content
})
})));
});
service.signup('', [], []).subscribe(
suc => expect(suc).toBe(content)
);
}));
it(
'checkUser should return a response with a "contenu" parameter',
inject([SignupService, XHRBackend], (service: SignupService, mockBackEnd: MockBackend) => {
let content = 'anything';
mockBackEnd.connections.subscribe((connection: MockConnection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify({
contenu: content
})
})));
});
service.checkUser('').subscribe(
suc => expect(suc).toBe(content)
);
}));
});
哇,我去了一個星期的假,在工作,完全忘記了這個職位(我已經放棄了,決定不進行測試)。你的解決方案確實有效,這太棒了!謝謝老兄 – trichetriche