Как проверить кеширование угловых данных? - PullRequest
0 голосов
/ 24 апреля 2019

У меня есть угловой сервис, который общается с нашим API.Некоторые запросы на одни и те же данные могут кэшироваться локально, чтобы помочь вещам чувствовать себя немного быстрее.

Вот в основном то, что происходит в методе службы, который выполняет некоторое кэширование:

private thingCache: IThing[] = [];

getThing$(thingId: string): Observable<IThing> {
    const cachedThing = this.thingCache.find(( => l.id === thingId);
    if (cachedThing) {
        return of(cachedThing);
    }
    const fetchedThing$ =  this.http.get<IThing>(`http://our-api/thing/${thingId}`)

    .pipe(tap((thing: IThing) => {
        //add any retrieved login to the cache
        //we already checked above that it's not in the cache, so we know we are adding a new one here
        this.thingCache.push(thing);
    }));

    return fetchedThing$;
}

Так что вtest Мне нужно проверить, что первый вызов происходит из фактического HTTP-запроса GET, а любой вызов после этого - нет.Какой лучший способ сделать это?

Вот как я проверяю первый звонок, который работает

describe('Service: api', () => {
    let service: ApiService;
    let httpMock: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ HttpClientTestingModule ],
            providers: [ ApiService ]
        });
        service = TestBed.get(ApiService);
        httpMock = TestBed.get(HttpTestingController);
    });

    afterEach(() => {
        httpMock.verify();
    });

    it('should GET a thing when calling getThing$() with a thing ID', () => {
        service.getThing$('1234-5678-9012').subscribe((value: IThing) => {
            expect(value).toEqual({
                id: '148e265b-b284-84b7-b8b3-441854f15783', otherData: 'foo'
            } as IThing);
        }, () => {
            fail('The subscription to getThing$() has errored out!');
        });

        const req = httpMock.expectOne('http://our-api/thing/1234-5678-9012');
        expect(req.request.method).toEqual('GET');

        req.flush({
            id: '148e265b-b284-84b7-b8b3-441854f15783', otherData: 'foo'
        } as IThing);
    });
});

1 Ответ

0 голосов
/ 25 апреля 2019

Ну, это оказалось немного проще, чем я думал.просто отмените подписку, а затем сделайте это снова.

it('should return a thing from the API on the first call, and from cache on the 2nd call for the same data', () => {
    const sub1 = service.getThing$('148e265b-b284-84b7-b8b3-441854f15783').subscribe((value: IThing) => {
        expect(value).toEqual({
            id: '148e265b-b284-84b7-b8b3-441854f15783', otherData: 'foo'
        } as IThing);
    }, () => {
        fail('The subscription to getThing$() has errored out!');
    });

    const req = httpMock.expectOne('http://our-api/thing/148e265b-b284-84b7-b8b3-441854f15783');
    expect(req.request.method).toEqual('GET');

    req.flush({
        id: '148e265b-b284-84b7-b8b3-441854f15783', otherData: 'foo'
    } as IThing);

    //----------------------------------------------------------------------
    //Ensure a 2nd call for the same ID does not make an HTTP call

    sub1.unsubscribe();

    const sub2 = service.getThing$('148e265b-b284-84b7-b8b3-441854f15783').subscribe((value: IThing) => {
        expect(value).toEqual({
            id: '148e265b-b284-84b7-b8b3-441854f15783', otherData: 'foo'
        } as IThing);
    }, () => {
        fail('The subscription to getThing$() has errored out!');
    });

    httpMock.expectNone('http://our-api/thing/148e265b-b284-84b7-b8b3-441854f15783');

    //----------------------------------------------------------------------
    //Ensure a 3rd call for a DIFFERENT ID still makes an HTTP request for the new un-cached data

    sub2.unsubscribe();

    service.getThing$('111e2222-bbbb-8888-cccc-444455555777').subscribe((value: IThing) => {
        expect(value).toEqual({
            id: '111e2222-bbbb-8888-cccc-444455555777', otherData: 'bar'
        } as IThing);
    }, () => {
        fail('The subscription to getThing$() has errored out!');
    });

    const req3 = httpMock.expectOne('http://our-api/thing/111e2222-bbbb-8888-cccc-444455555777');
    expect(req3.request.method).toEqual('GET');

    req3.flush({
        id: '111e2222-bbbb-8888-cccc-444455555777', otherData: 'bar'
    } as IThing);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...