我有一个角度组件,它将一些数据发送到我们的应用程序中的URL,然后不执行任何其他操作,因为没有数据从该帖子返回。我无法测试这个,因为通常会通过订阅他们返回的observable来测试HTTP请求。在这种情况下,不需要暴露这种情况。
这是我的组件代码:
shareData(): void {
this.isFinishing = true;
this.myService.sendSharedData$()
.pipe(first())
.subscribe(() => {
//Data s now shared, send the request to finish up everything
this.submitFinishRequest();
}, (e: Error) => this.handleError(e)));
}
private submitFinishRequest(): void {
//submit data to the MVC controller to validate everything,
const data = new FormData();
data.append('ApiToken', this.authService.apiToken);
data.append('OrderId', this.authService.orderId);
this.http.post<void>('/finish', data)
.pipe(first())
.subscribe((d) => {
// The controller should now redirect the app to the logged-out MVC view, so there's nothing more we need to do here
this.isFinishing = false;
}, (e: Error) => this.handleError(e));
}
这是我的测试代码
let component: FinishComponent;
let fixture: ComponentFixture<FinishComponent>;
let myService: MyService;
let httpMock: HttpTestingController;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
declarations: [ FinishComponent ],
providers: [ MySerVice ],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FinishComponent);
component = fixture.componentInstance;
myService = TestBed.get(MyService);
httpMock = TestBed.get(HttpTestingController);
sendSharedData$Spy = spyOn(myService, 'sendSharedData$');
//Add some accounts and shared items to the service for all of these tests
accountsService.dataToShare = ['foo', 'bar'];
});
afterEach(() => {
httpMock.verify();
});
it('should make an HTTP POST to the `/finish` MVC Controller after successfully sharing data', () => {
sendSharedData$Spy.and.callThrough(); //call through using data provided in `beforeEach`
fixture.detectChanges(); //triggers ngOnInit()
component.shareData();
fixture.detectChanges();
const req = httpMock.expectOne('/finish');
expect(req.request.method).toEqual('POST');
expect(req.request.body).toEqual({
apiKey: 'api-key-98765',
orderId: 'order-id-12345'
});
//server can send back any data (except for an error) and we would respond the same way, so just send whatever here
req.flush('');
});
我在测试中得到的是:
Error: Expected one matching request for criteria "Match URL: /finish", found none.
我认为这是因为我没有从我的测试中订阅http.post()
,但是如果我这样做并不完全否定我正在测试这种方法的原因?如果我的方法已经这样做,我不应该订阅东西,对吧?
另外,当我用其他测试运行时,另一个不相关的测试通常会失败
Error: Expected no open requests, found 1: POST /finish
这向我表明请求正在发生,但是在不正确的时间,或者我没有正确地等待它。
问题是由于.and.callThrough()
。我用.and.returnValue(of([... some data here ...]));
替换它,现在它按预期工作。对不起,麻烦,感谢所有的帮助和想法!
尝试使用您的服务调用该方法:myService [“sendSharedData”]().subscribe();当您想要调用私有方法时,可以使用此方法。你不再需要间谍,它应该工作。我希望 :) 。