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