CBa*_*arr 7 karma-jasmine angular angular-httpclient angular-test
我有一个 angular 组件,它将一些数据发布到我们应用程序中的 URL,然后什么都不做,因为没有数据从该帖子返回。我在测试这个时遇到了麻烦,因为通常 HTTP 请求是通过订阅它们返回的 observable 来测试的。在这种情况下不需要暴露。
这是我的组件代码:
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));
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试代码
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('');
});
Run Code Online (Sandbox Code Playgroud)
我在测试中实际得到的是:
Error: Expected one matching request for criteria "Match URL: /finish", found none.
Run Code Online (Sandbox Code Playgroud)
我认为发生这种情况是因为我没有http.post()从我的测试中订阅,但是如果我这样做并没有完全否定我测试这个方法的原因?如果我的方法已经这样做了,我不应该订阅东西,对吗?
另外,当我用其他测试运行它时,另一个不相关的测试通常会失败
Error: Expected no open requests, found 1: POST /finish
Run Code Online (Sandbox Code Playgroud)
这向我表明请求正在发生,但时间不正确,或者我没有正确等待它。
该问题是由于.and.callThrough(). 我用.and.returnValue(of([... some data here ...]));它替换了它,现在一切都按预期工作。很抱歉给您带来麻烦,感谢您的所有帮助和想法!
Rob*_*Tab -1
尝试在测试中使用您的服务调用该方法: myService ["sendSharedData"] ().subscribe(); 当您想要调用私有方法时,可以使用此方法。你不再需要间谍了,它应该可以工作。我希望 :) 。