角度测试HTTP Post调用

时间:2019-04-29 19:03:03

标签: angular karma-jasmine angular-httpclient angular-test angular-testing

我有一个角度组件,它将一些数据发布到我们应用程序中的URL,然后什么也不做,因为没有数据从该发布返回。我很难对此进行测试,因为通常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 ...]));,现在一切正常。很抱歉给您带来麻烦,感谢您提供的所有帮助和想法!

1 个答案:

答案 0 :(得分:0)

尝试使用您的服务在测试中调用该方法: myService [“ sendSharedData”]().subscribe(); 当您要调用私有方法时,可以使用这种方法。您不再需要间谍,它应该可以工作。我希望 :) 。