Angular 测试 HTTP Post 调用

标签 angular karma-jasmine 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));
}

这是我的测试代码

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();
当您想调用私有(private)方法时,您可以使用这种方法。您不再需要 spy ,它应该可以工作。我希望 :) 。

关于Angular 测试 HTTP Post 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55909361/

相关文章:

angular - odoo 服务器错误日志 : Function declared as capable of handling request of type 'json' but called with a request of type 'http'

css - 如何突出显示多个 ionic 列表中的选定元素?

angularjs - $httpBackend ExpectGET 未返回预期数据

javascript - Angular 2 - 在不使用 HTML 输入/文本区域的情况下获取条形码扫描器数据

angular - 在 Azure Pipelines 中集成 Angular 测试用例

angular - 无法读取未定义的属性 'ngOnInit' 'getData' -Angular-单元测试-jasmine

Angular HttpClient 缺少响应 header

html - Angular-如何模拟HttpErrorResponse?

angular - 将数据从子组件传递到父组件

angular - 如何使用mat-tab? mat-tab is not a known element 错误