如何使用HttpTestingController.expectOne匹配任何URL?

时间:2018-11-13 10:31:47

标签: angular unit-testing

expectOne()需要一个URL字符串以匹配被测代码通过HttpClient发出的请求。但是,我需要单独的测试来验证请求URL和验证结果数据。我想要一个测试来验证请求的URL(忽略结果数据),我可以编写该请求。而且我想要另一个测试来验证结果数据-无论URL是什么-我无法编写,因为ExpectOne要求URL参数要匹配。

我在寻找一种方法来告诉ExpectOne忽略URL或匹配任何URL,但是什么也没找到。我确实尝试传递“ *”,但这没用。

有没有办法让HttpTestingController匹配任何URL?

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { OperationsLogService } from './operations-log.service';
import { Severity } from './severity.enum';

describe('OperationsLogService', () => {
    let service: OperationsLogService;
    let httpMock: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule
            ],
            providers: [
                OperationsLogService
            ]
        });

        service = TestBed.get(OperationsLogService);
        httpMock = TestBed.get(HttpTestingController);
    });
    it('requests by page and max-count', (done) => {
        service
            .getEntries(3, 5)
            .subscribe((res: any) => {
                done();
            });
        const request = httpMock.expectOne('api/operations-log/oplog.json?page=3&max-count=5');
        request.flush({});
        httpMock.verify();
    });
    it('provides entries', (done) => {
        const entries = [
            {
                severity: Severity.Informational,
                whenLogged: Date.now(),
                code: 123,
                message: 'msg'
            }
        ];
        service
            .getEntries(3, 5)
            .subscribe((res: any) => {
                expect(res).toEqual(entries);
                done();
            });
        // don't want to specify the URL here
        const request = httpMock.expectOne('api/operations-log/oplog.json?page=3&max-count=5');
        request.flush(entries);
        httpMock.verify();
    });
});

为什么要使用此功能:测试应该相互独立。一个问题/更改应导致尽可能少的测试失败。如果URL测试失败,那么我不希望其他测试(提供条目)失败。有人建议我将URL存储在一个公共变量中。那确实消除了代码重复,但是测试仍然很薄弱。如果一个失败(由于URL更改),它们都会失败。

1 个答案:

答案 0 :(得分:0)

expectOne()有一个重载,可以满足您的需要(请参见http://wordpress.liquid.info/10/reverse-css/frode/上的文档):

  abstract expectOne(matchFn: ((req: HttpRequest<any>) => boolean), description?: string): TestRequest

因此,为了使您的测试与任何URL匹配,只需对匹配谓词的每次调用都返回true

  const request = httpMock.expectOne(() => true);
  request.flush(entries);